You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
78 lines
2.8 KiB
78 lines
2.8 KiB
using System;
|
|
using System.Collections.Generic;
|
|
using System.Text;
|
|
using System.Net;
|
|
using System.Net.Sockets;
|
|
using System.Threading;
|
|
using SocketProgram;
|
|
using System.Globalization;
|
|
|
|
namespace TcpServerLib
|
|
{
|
|
public class TcpServer
|
|
{
|
|
private byte[] buffer = new byte[1024];
|
|
public static readonly int maxLinkNum = 10;
|
|
public static int nowNum = 0;
|
|
private static readonly string logPath = "../log/Server.log";
|
|
private int port;
|
|
private IPEndPoint ipEndPoint;
|
|
private Socket mServerSocket;
|
|
private List<Socket> mClientSockets;
|
|
|
|
|
|
public TcpServer(int port)
|
|
{
|
|
this.port = port;
|
|
this.mClientSockets = new List<Socket>();
|
|
this.ipEndPoint = new IPEndPoint(IPAddress.Any, port);
|
|
this.mServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
|
|
this.mServerSocket.Bind(this.ipEndPoint);
|
|
}
|
|
|
|
public void Listen()
|
|
{
|
|
while (nowNum <= maxLinkNum)
|
|
{
|
|
this.mServerSocket.Listen(0);
|
|
Socket CliSocket = this.mServerSocket.Accept();
|
|
this.mClientSockets.Add(CliSocket);
|
|
var mReveiveThread = new Thread(this.ReceiveClient);
|
|
mReveiveThread.Start(CliSocket);
|
|
++nowNum;
|
|
string str = "链接成功:now_link_num[" + nowNum + "]";
|
|
string ep = CliSocket.RemoteEndPoint.ToString();
|
|
SocketClass.WriteLog(logPath, SocketClass.GetNowTimeStr() + str);
|
|
SocketClass.WriteLog(logPath, ep);
|
|
}
|
|
}
|
|
|
|
private void ReceiveClient(object obj)
|
|
{
|
|
var mClientSocket = (Socket)obj;
|
|
while (true)
|
|
{
|
|
try
|
|
{
|
|
int receiveLength = mClientSocket.Receive(buffer);
|
|
string clientMessage = Encoding.UTF8.GetString(buffer, 0, receiveLength);
|
|
//SocketClass.DealRecvMsg(logPath, clientMessage,true);
|
|
string returnStr = "recv_success" + clientMessage;
|
|
mClientSocket.Send(Encoding.UTF8.GetBytes(returnStr));
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
this.mClientSockets.Remove(mClientSocket);
|
|
string estr = e.ToString();
|
|
SocketClass.WriteLog(logPath, SocketClass.GetNowTimeStr() + estr);
|
|
mClientSocket.Shutdown(SocketShutdown.Both);
|
|
mClientSocket.Close();
|
|
--nowNum;
|
|
string str = "链接断开:now_link_num[" + nowNum + "]";
|
|
SocketClass.WriteLog(logPath, SocketClass.GetNowTimeStr() + str);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|