我收到数据时有一个奇怪的错误。基本上发生的是您从一个客户端发送数据,并且您可以再次发送数据,但是如果您从第二个客户端发送数据,则服务器不会在第一次接收数据而您必须再次发送数据。然后你必须回到你的其他客户端并再次发送数据两次,服务器才能接收一次。
我不知道这可能是什么,我认为可能是问题的代码,请告诉我是否有其他任何我可以提供的帮助我,谢谢你提前!
来自服务器:
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);
}
}
发送:来自客户
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());
}
}