异步套接字接收/发送不接收/发送第一个字节

时间:2013-10-10 18:08:27

标签: c# sockets asynchronous

我正在尝试为多人制作一个基本的聊天系统。 它发送消息和所有消息,但除了从每个客户端发送的第一个消息之外,每个消息的第一个字节都丢失了(客户端是否未发送它,或者服务器没有收到它)。 这是我的客户端的Send和SendCallback:

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” 服务器看到“我” - 第一个字符丢失。

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

0 个答案:

没有答案