public class Server
{
private TcpListener tcpListener;
private Thread listenThread;
private List<TcpClient> clientLists;
private delegate void getLineHandler(string line);
private event getLineHandler getLine;
public delegate void connectFailedHandler();
public event connectFailedHandler connectFailed;
public Server()
{
this.tcpListener = new TcpListener(IPAddress.Parse("127.0.0.1"), 8044);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
clientLists = new List<TcpClient>();
this.listenThread.Start();
}
public void Abort()
{
tcpListener.Server.Close();
listenThread.Abort();
foreach(var t in clientLists)
{
t.Close();
}
}
private void ListenForClients()
{
this.tcpListener.Start();
while (true)
{
//阻塞
TcpClient client = this.tcpListener.AcceptTcpClient();
//创建处理线程
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
clientLists.Add(client);
}
}
private void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
Debug.WriteLine("Client @[{0}] connected @{1}", tcpClient.Client.LocalEndPoint, DateTime.Now.ToString());
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead = 0;
//bool isRight=false;
while (tcpClient.Connected)
{
bytesRead = 0;
try
{
bytesRead = clientStream.Read(message, 0, 4096);
}
catch
{
Debug.WriteLine("Error:receive msg error");
break;
}
if (bytesRead == 0)
{
//断开
Debug.WriteLine("Client @[{0}] disconnect @{1}", tcpClient.Client.LocalEndPoint, DateTime.Now.ToString());
break;
}
//获取
ASCIIEncoding encoder = new ASCIIEncoding();
//System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
string recvstr = encoder.GetString(message, 0, bytesRead);
getLine?.Invoke(recvstr);
Debug.WriteLine("Recv:[{1}]:msg:@[{0}] @{2}", recvstr, tcpClient.Client.LocalEndPoint, DateTime.Now.ToString());
//返回数据
string sendstr = "0";
byte[] buffer = encoder.GetBytes(sendstr);
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
tcpClient.Close();
connectFailed?.Invoke();
}
}
本文标题:C#:TCPServer实现(初步)
本文连接:https://blog.dextercai.com/archives/109.html
除另行说明,本站文字内容采用创作共用版权 CC-BY-NC-ND 4.0 许可协议,版权归本人所有。
除另行说明,本站图片内容版权归本人所有,未经许可前,严禁以任何形式的使用。
即日起视情况关闭全站评论区,您可以通过关于页面的电邮地址和我取得联系,谢谢