我是 C#、OOP、网络和 TCP/IP 套接字的新手...
我对异步 TCP/IP 套接字通信的使用有误解。我正在尝试创建一个等待多个客户端的服务器,并且每次客户端连接时,它都会显示类似“用户 192.168.1.105:2421 已加入”的内容
我认为当您使用 BeginAccept() 时,将创建一个新线程……每当有新用户连接时,它将负责与该特定客户端的通信。但是,以下代码块......并且不显示第二个客户端的消息。
我应该改变什么,以便为每个连接的客户端我有一个单独的线程来处理执行?
class Server
{
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//constructor
public Server()
{
listener.Bind(new IPEndPoint(IPAddress.Parse("192.168.1.100"), 9050));
listener.Listen(10);
listener.BeginAccept(new AsyncCallback(OnConnectRequest), listener);
Console.Write("Server Running...\r\n");
}
public void OnConnectRequest(IAsyncResult ar)
{
Socket listener = (Socket)ar.AsyncState;
NewConnection(listener.EndAccept(ar));
listener.BeginAccept(new AsyncCallback(OnConnectRequest), listener);
}
//send a string message over a TCP socket
public void sendMSG(string msg,Socket socket)
{
//some code which sends data according to my protocol
}
public byte[] receiveMSG(ref Socket socket)
{
//some code which receives data according to my protocol
}
//function called whenever a NEW CLIENT is connected
public void NewConnection(Socket sockClient)
{
Console.WriteLine("user {0} has joined",sockClient.RemoteEndPoint);
byte[] msg = new byte[20];
sockClient.Receive(msg);
}