此代码表示服务器的操作:
private Socket _listenSocket;
public event EventHandler Accept;
protected virtual void OnAccept(ListenEventArgs args)
{
EventHandler handler = Accept;
if (handler != null)
handler(this, args);
}
public void Start()
{
StillListen = true;
_listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
var localEp = new IPEndPoint(IPAddress.Parse("127.0.0.1"), _port);
_listenSocket.Bind(localEp);
_listenSocket.Listen(100);
AcceptClient();
}
public void Stop()
{
StillListen = false;
//_listenSocket.EndAccept();
_listenSocket.Dispose();
}
private void AcceptClient()
{
_listenSocket.BeginAccept(Accepted, null);
}
private void Accepted(IAsyncResult result)
{
var client = _listenSocket.EndAccept(result);
if (StillListen)
{
_listenSocket.BeginAccept(Accepted, null);
OnAccept(new ListenEventArgs(client));
}
}
如果我想停止听众,我该怎么做? _listenSocket仍在等待接受客户端,但在处理_listenSocket后触发异常: 无法访问被处置对象(在接受无效的内部)。
请帮助。