我正在尝试将IAsyncResult.AsyncState强制转换为类StateObject。但由于AsyncState的类型为Socket,因此它会发出强制转换错误。我需要从结果中获取字节数据。我刚刚开始了一个服务器项目,我对此并不熟悉。
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 256;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}
这是OnReceiveHandlerClass
private void Receive(IAsyncResult result)
{
StateObject ss = (StateObject)result.AsyncState;
......
}
提前致谢..
答案 0 :(得分:0)
我收到错误是因为我在BeginReceive方法中发送了一个不同的对象,以防发送StateObject
Correct method:
Socket.BeginReceive(StateObject.DataBuffer, 0, (int)StateObject.DataLength,
SocketFlags.None, new AsyncCallback(this.Receive),StateObject);
最后一个参数应该是StateObject类型,我发送一个对象,因为我不知道该为该参数发送什么。