TCP异步套接字

TCP async Socket

我正在创建一个异步 TCP 服务器,它的工作方式有点像聊天室,或者至少应该如此。当新客户端连接到服务器时,他会收到一条欢迎消息,并且每次他发送消息时,服务器都会回显。当只有一个客户端连接时它工作正常,但是当另一个客户端连接时,他没有收到欢迎消息和回显。

这是我的一些代码。

private void btn_startserver_Click(object sender, EventArgs e)
{
    server = new Socket(AddressFamily.InterNetwork,
        SocketType.Stream, ProtocolType.Tcp); //Populates the Server obj. 
    IPEndPoint iep = new IPEndPoint(IPAddress.Any, 23);
    server.Bind(iep);
    server.Listen(5);
    server.BeginAccept(new AsyncCallback(AcceptConn), server);
    WriteOnLog("Waiting for incoming connections...");
    Thread t1 = new Thread(() => verifyCon(server));
    t1.Start();
}

public void AcceptConn(IAsyncResult iar)
{
    Socket oldserver = (Socket)iar.AsyncState;
    Socket client = oldserver.EndAccept(iar);
    clientList.Add(client);
    WriteOnLog("Connected to: " + client.RemoteEndPoint.ToString());
    string stringData = "Connected Successfully\r\nWelcome to the Server\r\n";
    byte[] message1 = Encoding.UTF8.GetBytes(stringData);
    client.BeginSend(message1, 0, message1.Length, SocketFlags.None,
        new AsyncCallback(SendData), client);
    WriteOnClients(client.RemoteEndPoint.ToString(), "add");
}

void SendData(IAsyncResult iar)
{
    Socket client = (Socket)iar.AsyncState;
    int sent = client.EndSend(iar);
    client.BeginReceive(data, 0, size, SocketFlags.None,
        new AsyncCallback(ReceiveData), client);
}

void ReceiveData(IAsyncResult iar)
{
    Socket client = (Socket)iar.AsyncState;
    string curClient = client.RemoteEndPoint.ToString();
    int recv = client.EndReceive(iar);
    if (recv == 0)
    {
        client.Close();
        WriteOnLog("Connection lost with " + curClient);
        WriteOnClients(curClient, "remove");
        WriteOnLog("Waiting for client...");
        connectedClients.Remove(curClient);
        server.BeginAccept(new AsyncCallback(AcceptConn), server);
        return;
    }
    string receivedData = Encoding.ASCII.GetString(data, 0, recv);
    WriteOnLog(receivedData);
    byte[] message2 = Encoding.UTF8.GetBytes(receivedData);
    client.BeginSend(message2, 0, message2.Length, SocketFlags.None,
        new AsyncCallback(SendData), client);
}

处理完第一个传入连接 (EndAccept) 后,您需要再次调用 BeginAccept 以接受下一个连接。

目前您仅在初始化期间调用 BeginAccept,并且当客户端 断开连接时