C# socke TCP 异步通信 接收消息缓冲区怎么弄,新手
public static string GetMinShenResponse(string xml,string fn)
{
var requestbyte = GetRequest(xml, fn);
string result = string.Empty;
byte[] buffer = new byte[1024];
//定义套接字类型
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
clientSocket.Connect(MsServerUrl, int.Parse(Msport));
}
catch (SocketException e)
{
throw (e);//暂时不做处理
}
//发送心跳包
clientSocket.Send(Encoding.UTF8.GetBytes("00000000"));
//发送消息
Task.Run(() =>
{
clientSocket.Send(requestbyte);
});
//接受消息
Task.Run(() =>
{
int length = clientSocket.Receive(buffer);//获取的数据长度
int isnum = 0;//用来记录一个报头的报文总长度
byte[] baotoubyte = new byte[8];
//截取包头
Array.Copy(buffer, 0, baotoubyte, 0, baotoubyte.Length);
string baotou = Encoding.Default.GetString(baotoubyte);
if (int.TryParse(baotou, out isnum))
{
if (isnum == length - 8)//完整包
{
byte[] actually = new byte[length - 284];//数据包长度
Array.Copy(buffer, 284, actually, 0, actually.Length);
result = RSADecrypt(actually);
}
else if (isnum < length - 8)//处理粘包
{
byte[] actually = new byte[isnum - 276];//数据包长度
Array.Copy(buffer, 276, actually, 0, actually.Length);
result = RSADecrypt(actually);
}
else //断包
{
}
}
else
{
//包结构不对
}
});
return result;
}