我贴一下具体代码吧[C#] 纯文本查看 复制代码 public void RecevieMsg(object socket)
{
Socket newSocket = socket as Socket;
while (true)
{
byte[] buffer1 = new byte[1024 * 1024 * 2];
try
{
//这个一次接收不完整,一次只接收1024,
//int receiveLength = newSocket.Receive(buffer);
//if (receiveLength>0)
//{
// string str = Encoding.Default.GetString(buffer);
// MemoryStream mStream = new MemoryStream();
// BinaryFormatter bFormat = new BinaryFormatter();
// mStream.Write(buffer, 0, buffer.Length);
// mStream.Flush();
// mStream.Position = 0;
// AgreementInfo agm = new AgreementInfo();
// agm = (AgreementInfo)bFormat.Deserialize(mStream);
// this.ReceiveEvent(agm);
//}
int receiveLength=0;
byte[] buffer = new byte[1024];
while (true)
{
//循环几次后就会被Receive阻塞
receiveLength = newSocket.Receive(buffer);
if (receiveLength < 1)
{
break;
}
}
MemoryStream mStream = new MemoryStream();
BinaryFormatter bFormat = new BinaryFormatter();
mStream.Write(buffer, 0, buffer.Length);
mStream.Flush();
mStream.Position = 0;
AgreementInfo agm = new AgreementInfo();
agm = (AgreementInfo)bFormat.Deserialize(mStream);
this.ReceiveEvent(agm);
}
catch (SocketException ex)
{
SocketEx.Write(ex.Message);
break;
}
catch (ObjectDisposedException ex)
{
SocketEx.Write(ex.Message);
break;
}
catch (Exception ex)
{
SocketEx.Write(ex.Message);
break;
}
}
}
|