C# 套接字接收数据错误
我在接收数据方面有一个奇怪的错误。基本上,您可以从一个客户端发送数据,也可以再次发送数据,但是如果您从第二个客户端发送数据,服务器第一次就不会收到数据,您必须再次发送数据。然后,您必须返回到另一个客户机并再次发送两次数据,以便服务器接收一次数据 我不知道这可能是什么,这里是代码,我认为可能是问题,让我知道,如果有什么我可以提供给你,以帮助我,在先进的感谢 从服务器:C# 套接字接收数据错误,c#,sockets,C#,Sockets,我在接收数据方面有一个奇怪的错误。基本上,您可以从一个客户端发送数据,也可以再次发送数据,但是如果您从第二个客户端发送数据,服务器第一次就不会收到数据,您必须再次发送数据。然后,您必须返回到另一个客户机并再次发送两次数据,以便服务器接收一次数据 我不知道这可能是什么,这里是代码,我认为可能是问题,让我知道,如果有什么我可以提供给你,以帮助我,在先进的感谢 从服务器: public void beginReceive(object handler_obj){ Socket handler
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());
}
}