我正在开发一个appserver。我想使用AcceptAsync方法。我收到错误“对象引用没有设置为对象的实例。”调用ReceiveAsync方法时。如果有任何问题并得到解决方案吗?
public class AppServer
{
public void Start()
{
Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(new IPEndPoint(IPAddress.Any, 12345));
serverSocket.Listen(100);
SocketAsyncEventArgs e = new SocketAsyncEventArgs();
e.Completed += new EventHandler<SocketAsyncEventArgs>(e_Completed);
bool raiseEvent = serverSocket.AcceptAsync(e);
if (!raiseEvent)
AcceptCallback(e);
}
void e_Completed(object sender, SocketAsyncEventArgs e)
{
AcceptCallback(e);
}
private void AcceptCallback(SocketAsyncEventArgs e)
{
SocketAsyncEventArgs readEventArgs = new SocketAsyncEventArgs();
readEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(readEventArgs_Completed);
Socket clientSocket = e.AcceptSocket;
bool raiseEvent = clientSocket.ReceiveAsync(readEventArgs); // <-- Error goes here
if (!raiseEvent)
ReceiveCallback(readEventArgs);
}
void readEventArgs_Completed(object sender, SocketAsyncEventArgs e)
{
ReceiveCallback(e);
}
private void ReceiveCallback(SocketAsyncEventArgs e)
{
}
}
答案 0 :(得分:7)
我有同样的问题,我设法解决了。 您需要向SocketAsyncEventArgs对象提供一个数据缓冲区(字节数组),用于存储在调用ReceiveAsync(e)之前接收的数据。
void e_Completed(object sender, SocketAsyncEventArgs e)
{
byte[] buffer = new byte[1024];
e.SetBuffer(buffer, 0, buffer.Length);
AcceptCallback(e);
}
答案 1 :(得分:-1)