public class SimpleTcpServer
{
private int networkPort;
private bool isWaitingListen = true;
private bool isWaitingRecieve = true;
private System.Net.Sockets.Socket listenSocket;
public void NetworkStart(int networkPort)
{
this.networkPort = networkPort;
this.listenSocket = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
var serverEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Any, networkPort);
this.listenSocket.Bind(serverEndPoint);
this.listenSocket.Listen(10);
// 启动监听线程
new System.Threading.Thread(Listen) { IsBackground = true }.Start(listenSocket);
}
private void Listen(object obj)
{
if (!(obj is System.Net.Sockets.Socket socket)) return;
while (isWaitingListen)
{
// 阻塞函数
var currentSocket = socket.Accept();
isWaitingRecieve = true;
if (this.isWaitingRecieve)
{
// 延迟是为了保证数据处理完成
System.Threading.Thread.Sleep(100);
isWaitingRecieve = false;
System.Threading.Thread.Sleep(200);
}
if (currentSocket.Connected)
{
// 启动接收线程
new System.Threading.Thread(ReceiveData) { IsBackground = true }.Start(currentSocket);
}
}
}
private void ReceiveData(object obj)
{
if (!(obj is System.Net.Sockets.Socket socket)) return;
while (isWaitingRecieve)
{
var receiveBuffer = new byte[1024];
// 数据接受缓冲
System.Threading.Thread.Sleep(50);
// 阻塞函数
var size = socket.Receive(receiveBuffer);
if (size > 0)
{
var receivedData = System.Text.Encoding.UTF8.GetString(receiveBuffer, 0, size);
// 执行数据处理
// TODO
}
}
}
public void NetworkClose()
{
if (this.isWaitingListen)
{
// 阻止再次进入等待连接状态
this.isWaitingListen = false;
// 通过重新连接,正式解除监听SOCKET的当前阻塞状态
using (var client = new System.Net.Sockets.TcpClient())
{
client.Connect("127.0.0.1", this.networkPort);
client.Close();
}
}
if (this.isWaitingRecieve)
{
// 延迟是为了保证数据处理完成
System.Threading.Thread.Sleep(100);
isWaitingRecieve = false;
System.Threading.Thread.Sleep(200);
}
listenSocket?.Close();
}
}
【CSharp】简单的TCP/IP服务器
最新推荐文章于 2024-08-03 22:12:17 发布