0

我正在尝试为多人制作一个基本的聊天系统。它发送消息和所有消息,但除了每个客户端发送的第一条消息外,每个消息的第一个字节都丢失了(无论客户端没有发送它,还是服务器没有接收到它)。这是我客户的发送和发送回调:

private static void Send(Socket client, string data)
{
    byte[] byteData = Encoding.ASCII.GetBytes(data);
    client.BeginSend(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(SendCallback), client);
}

private static void SendCallback(IAsyncResult ar)
{
    try
    {
        Socket client = (Socket) ar.AsyncState;
        int bytesSent = client.EndSend(ar);
        sendDone.Set();
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
    }
}

这是我服务器的 Accepter 和 ReceiveCallback:

private static void AcceptCallback(IAsyncResult ar)
{
    allDone.Set();

    Socket listenerSocket = (Socket) ar.AsyncState;
    Socket handlerSocket = listenerSocket.EndAccept(ar);
    if (!clientList.Contains(handlerSocket))
    {
        clientList.Add(handlerSocket);
    }
    // Creating the state object
    StateObject state = new StateObject();
    state.workSocket = handlerSocket;
    handlerSocket.BeginReceive(state.buffer, 0, StateObject.BUFFER_SIZE, 0,
        new AsyncCallback(ReceiveCallback), state);
}

private static void ReceiveCallback(IAsyncResult ar)
{
    StateObject state = (StateObject) ar.AsyncState;
    Socket handlerSocket = state.workSocket;

    // Read data from the client socket.
    try
    {
        int read = handlerSocket.EndReceive(ar);
        if (read > 0)
        {
            state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, read));
            handlerSocket.BeginReceive(state.buffer, 0, StateObject.BUFFER_SIZE, 0, new AsyncCallback(ReceiveCallback),
                state);
        }


        if (state.sb.Length > 0)
        {
            string content = state.sb.ToString();
            foreach (Socket clientSocket in clientList)
            {
                Send(clientSocket, content);
            }
            Console.WriteLine(content);
            state.sb = new StringBuilder();
        }
        else
            handlerSocket.Close();
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
    }
}

我将举一个问题的例子:
客户端发送“hi”,
服务器看到“hi”——一切都很好。
然后:
客户端发送“hi” 服务器看到“i” - 第一个字符丢失。

我错过了什么?我做错了什么?

4

0 回答 0