我刚注意到我的套接字客户端没有收到服务器发回给它的相同数据。文字在8192个字符后被删除。
我不知道有一些限制吗?我如何通过这个?
客户端使用此代码:
//Send and Receive
public string sendAndReceiveMSG(string msg)
{
try
{
NetworkStream serverStream = clientSocket.GetStream();
string sendresponse = sendMSG(msg, serverStream);
if (sendresponse == "ConnectionCrash")
{
return sendresponse;
}
else if (sendresponse == "OK")
{
string receiveresponse = receiveMSG(serverStream);
return receiveresponse;
}
return "UnknownErrorInternal";
}
catch (Exception ex)
{
return "UnknownErrorInternal";
}
}
//Send msg
private string sendMSG(string msg, NetworkStream serverStream)
{
try
{
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(msg);
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
return "OK";
}
catch (Exception ex)
{
endSock();
return "ConnectionCrash";
}
}
//Receive msg
private string receiveMSG(NetworkStream serverStream)
{
try
{
byte[] inStream = new byte[10025];
int buffSize = clientSocket.ReceiveBufferSize;
dynamic bytesRead = serverStream.Read(inStream, 0, buffSize);
string returndata = System.Text.Encoding.ASCII.GetString(inStream, 0, bytesRead);
return returndata;
}
catch (Exception ex)
{
endSock();
return "ConnectionCrash";
}
}
客户端然后从服务器获得响应,如此;
string recv = client.sendAndReceiveMSG("someRequest");
答案 0 :(得分:5)
您只处理了一次Read
来电。完全可以预料到这种行为;你很少将所有数据都记录在一个数据包中(坦白说,我很惊讶你没有及早发现它)。
您需要决定“框架”策略(即如何区分每个子消息 - 如果是基于文本的新行或二进制的长度前缀) - 并获得帧值得处理前的数据这通常意味着在循环中调用Read
,或者使用类似StreamReader
之类的东西调用ReadLine()
来处理(即在循环中调用Read
)。
如果套接字上只有一条消息,并且主叫方关闭了它们的连接,则可以省略框架,只需阅读{{1}}即可返回非正数(即EOF)。