我有Winform应用程序,我想创建多套接字服务器,假设每个线程将管理每个套接字服务器。我之前尝试过,但似乎不起作用。我不确定我是否在这里犯了一些错误,或者甚至我的想法很糟糕。请看下面的方法。
private void bt_multi_Click(object sender, EventArgs e)
{
var ip_port = new List<string>();
ip_port.Add("192.168.1.100#5555"); //open server in this port, listening any client incoming
ip_port.Add("192.168.1.100#6666"); //open server in this port, listening any client incoming
foreach (var item in ip_port)
{
var ip = item.Split('#')[0];
var port = int.Parse(item.Split('#')[1]);
TcpListener listener_multi = null;
Socket socket_multi = null;
NetworkStream stream_multi = null;
System.Threading.Thread thread = new System.Threading.Thread(() =>
{
_start_multi(listener_multi, socket_multi, stream_multi, ip, port);
});
thread.Start();
}
}
private async void _start_multi(TcpListener listener_multi, Socket socket_multi, NetworkStream stream_multi, string _ip, int _port)
{
try
{
listener_multi = new TcpListener(IPAddress.Parse(_ip), _port);
listener_multi.Start();
socket_multi = listener_multi.AcceptSocket();
socket_multi.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
socket_multi.SendTimeout = 180000;
socket_multi.ReceiveTimeout = 180000;
stream_multi = new NetworkStream(socket_multi);
while (true)
{
byte[] myReadBuffer = new byte[1024 * 5];
int numberOfBytesRead = 0;
rec_continute:
numberOfBytesRead = stream_multi.Read(myReadBuffer, 0, myReadBuffer.Length);
byte[] bytes_real = new byte[numberOfBytesRead];
Buffer.BlockCopy(myReadBuffer, 0, bytes_real, 0, numberOfBytesRead);
if (bytes_real.Length != 0)
{
//proceed with byte incoming from client
goto rec_continute;
}
if (bytes_real.Length == 0)
{
break;
}
}
}
catch (Exception ex)
{
if (socket_multi != null)
{
socket_multi.Close();
listener_multi.Stop();
socket_multi = null;
}
MessageBox.Show("Disconnected with client!!! " + ex.Message);
}
}
所以,对此有任何想法,请与我分享。谢谢!
编写一个像样的套接字服务器是很难;我在这里可以给出的最好答案是“不” - Kestrel(asp.net Web 服务器)可以充当套接字服务器,包括在
async
核心上构建的完整连接和缓冲区管理,让您只需要编写实际的协议代码。 这个类似 redis 的服务器实现中给出了一个示例,更多信息请参见这个由 4 部分组成的博客系列