在下面的代码状态中,是一个具有属性 msgLength 的对象,它是消息的总长度。msgLength 是消息的前四个字节。当在“快速”成功中收到多条消息时,我在 state.msgLength 属性中得到意外结果。当 state.msglength 不符合预期时,我在尝试接收时收到错误。指定的参数超出了有效值的范围。
StateObj state = (StateObj)ar.AsyncState;
try
{
state.read += state.socket.EndReceive(ar);
if (state.read == 0)
{
state.socket.Close();
state.socket.Dispose();
state.socket = null;
this.Invoke((MethodInvoker)delegate { listBox1.Items.Add(DateTime.Now.ToString("HH:mm ss") + " socket closed"); });
return;
}
}
catch (Exception)
{
this.Invoke((MethodInvoker)delegate { listBox1.Items.Add(DateTime.Now.ToString("HH:mm ss") + " socket closed"); });
return;
}
if (state.read < 4)
{
//read again you dont have state,msglength
state.socket.BeginReceive(state.dataBuffer, state.read, 4 - state.read, 0, cbReceive, state);
}
else
{
state.msglength = BitConverter.ToInt32(state.dataBuffer, 0);
}
if (state.read < state.msglength)
{
//read again you dont have the complete message
//here is the error Specified argument was out of the range of valid values.
state.socket.BeginReceive(state.dataBuffer, state.read, state.msglength - state.read, 0, cbReceive, state);
}
else
{
//process here
if (state.read > state.msglength )
{
state.read = state.read - state.msglength;
}
else
{
state.read = 0;
}
state.socket.BeginReceive(state.dataBuffer, 0, state.dataBuffer.Length, 0, cbReceive, state);
}