1

I have a strange bug with receiving data. Basically what happens is you send data from one client, and you can send data again, but if you send data from the second client, the server doesn't receive the data the first time and you have to send data again. then you have to go back to your other client and send data twice again for the server to receive it once.

I have no guess as to what this could be here is the code I think could be the problem, let me know if there's anything else I can supply for you to assist me, Thanks in advanced!

From Server:

public void beginReceive(object handler_obj){
    Socket handler = (Socket)handler_obj;

}

public void ReadCallback(IAsyncResult ar){
    Socket handler = (Socket)ar.AsyncState;
    try
    {
        int bytesRead = handler.EndReceive(ar);

        if (bytesRead > 0)
        {
            byte[] byteData = new byte[bytesRead];
            byteData = buffer;
            byte[] readData = new byte[byteData.Length - 1];
            Buffer.BlockCopy(byteData, 1, readData, 0, readData.Length);
            String data = Encoding.ASCII.GetString(readData);



            handlers.handleData(handlers.getHandlerType(byteData[0]), data, handler);

            buffer = new byte[BufferSize];

            handler.BeginReceive(buffer, 0, BufferSize, 0, new AsyncCallback(ReadCallback), handler);


        }
        else
        {
            handler.BeginReceive(buffer, 0, BufferSize, 0, new AsyncCallback(ReadCallback), handler);
        }
    }
    catch
    {
        Common common = new Common();
        common.appendLog("Error receiving data from " + handler.RemoteEndPoint);
    }

}

Send: From client

public void Send(String data, byte dataType)
{
    byte[] byteType = new byte[1];
    byteType[0] = dataType;

    int bufferSize = byteType.Length + Encoding.ASCII.GetBytes(data).Length;
    var ms = new MemoryStream(new byte[bufferSize], 0, bufferSize, true, true);
    ms.Write(byteType, 0, byteType.Length);
    ms.Write(Encoding.ASCII.GetBytes(data), 0, Encoding.ASCII.GetBytes(data).Length);

    byte[] byteData = ms.GetBuffer(); 

    sock.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), sock);
}

private static void SendCallback(IAsyncResult ar)
{
    try
    {
        Socket handler = (Socket)ar.AsyncState;
        int bytesSent = handler.EndSend(ar);
    }
    catch (Exception e)
    {
        MessageBox.Show(e.ToString());
    }
}
4

0 回答 0