我一直在努力通过网络为我一直在从事的一个小项目序列化一个对象。我使用的代码几乎完美无缺,有时字节无法正确加载,但只需重新加载 UI 即可解决。但是,当在同一个系统上进行通信时,但一旦您进入不同的系统,代码只能部分工作。一旦我尝试通过网络发送一个大小为 30 的字符串数组,服务器就会停止报告接收包,奇怪的是,没有任何东西会持续引发错误。有几个错误不时弹出:
System.InvalidOperationException: Cannot block a call on this socket while an earlier asynchronous call is in progress.
at System.Net.Sockets.Socket.ValidateBlockingMode()
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags, SocketError& errorCode)
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.Socket.Receive(Byte[] buffer)
at DMAssist.AsynchronousClient.Receive(Socket client) in C:\Users\crud4\documents\visual studio 2015\Projects\DMAssist\DMAssist\asyncsclient.cs:line 160
at DMAssist.AsynchronousClient.StartClient(Object obj, Boolean expectresponse) in C:\Users\crud4\documents\visual studio 2015\Projects\DMAssist\DMAssist\asyncsclient.cs:line 119
这是我在控制台中不断遇到的主要错误,我不知道如何处理它。我在网络编程方面不是很有经验,所以我不知道哪里出了问题。
我主要担心的是,由于某种原因,当客户端尝试发送超过 330 个字节时,服务器停止报告接收字节,并导致整体故障行为。服务器肯定会显示接收到连接,但由于某种原因,简单会立即将其终止。如果有人知道发生了什么或如何解决它,我将非常感谢您的帮助!
提前致谢!
客户:
private netObject Receive(Socket client)
{
byte[] buffer = new byte[1024];
int iRx = client.Receive(buffer);
object rawbytes = ByteArrayToObject(buffer);
netObject recvobject = (netObject)rawbytes;
receiveDone.Set();
return recvobject;
}
public netObject StartClient(Object obj, bool expectresponse)
{
// Connect to a remote device.
try
{
// Establish the remote endpoint for the socket.
// The name of the
// remote device is "host.contoso.com".
IPAddress ipAddress = IPAddress.Parse(ip);
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 25599);
// Create a TCP/IP socket.
Socket client = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Connect to the remote endpoint.
client.BeginConnect(remoteEP,
new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne();
// Send test data to the remote device.
Send(client, ObjectToByteArray(obj));
sendDone.WaitOne();
Send(client, Encoding.ASCII.GetBytes("<EOF>"));
sendDone.WaitOne();
// Receive the response from the remote device.
if (expectresponse)
{
netObject serverdata = Receive(client);
receiveDone.WaitOne();
return serverdata;
}
// Release the socket.
client.Shutdown(SocketShutdown.Both);
client.Close();
return new netObject();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return new netObject();
}
}
private static void Send(Socket client, byte[] data)
{
byte[] byteData = data;
// Begin sending the data to the remote device.
client.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), client);
}
服务器:
public void ReadCallback(IAsyncResult ar)
{
try {
String content = String.Empty;
// Retrieve the state object and the handler socket
// from the asynchronous state object.
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
// Read data from the client socket.
int bytesRead = handler.EndReceive(ar);
Console.WriteLine(bytesRead);
if (bytesRead > 0)
{
if (bytesRead != 5)
{
Array.Copy(state.buffer, state.cleanbuffer, bytesRead);
}
// There might be more data, so store the data received so far.
state.sb.Append(Encoding.ASCII.GetString(
state.buffer, 0, bytesRead));
// Check for end-of-file tag. If it is not there, read
// more data.
content = state.sb.ToString();
Console.WriteLine("SERVER: Recieved " + bytesRead + " bytes");
if (content.IndexOf("<EOF>") > -1)
{
// All the data has been read from the
// client. Display it on the console.
/*Console.WriteLine("Read {0} bytes from socket. Data : {1}",
content.Length, content);*/
object rawbytes = ByteArrayToObject(state.cleanbuffer);
netObject recvobject = (netObject)rawbytes;
}
// Echo the data back to the client.
Send(handler, ObjectToByteArray((object)recvobject));
}
else {
// Not all data received. Get more.
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
}
} catch (Exception e)
{
Console.WriteLine(e.StackTrace);
}
}
private void Send(Socket handler, byte[] data)
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = data;
// Begin sending the data to the remote device.
handler.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), handler);
}
private static void SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket handler = (Socket)ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = handler.EndSend(ar);
Console.WriteLine("Sent {0} bytes to client.", bytesSent);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}