2016-05-15 93 views
0

我正在嘗試基於異步套接字編寫簡單的客戶端服務器應用程序。一切工作正常,直到我嘗試連接多個客戶端。它們連接好,但只有「最新的一個」可以將數據發送到服務器,別人拋出異常:C#中的異步套接字

「並沒有返回IAsyncResult對象」

這裏是我的AcceptCallback代碼:

private void AcceptCallback(IAsyncResult AR) 
{ 
    try 
    { 
     _clientSocket = _serverSocket.EndAccept(AR); 
     _buffer = new byte[_clientSocket.ReceiveBufferSize]; 
     _clientSocket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null); 
     _serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null); 
     Console.WriteLine("Client connected!"); 
    } 
    catch (Exception ex) 
    { 
     Console.WriteLine(ex.Message); 
    } 
} 

任何想法有什麼不對?我在學習,所以它可能是一些愚蠢和明顯的東西,但我沒有看到它。

回答

1

通過指定_clientSocket = _serverSocket.EndAccept(AR);您鬆開了之前的_clientSocket;

我會改變你的代碼如下(主要是傳遞必要的信息,如套接字,緩衝區等ObjectState參數)。

的BeginXXX方法ObjectState參數.....

var tcpListener = new TcpListener(IPAddress.Any, 8088); 
tcpListener.Start(); 
tcpListener.BeginAcceptSocket(AsyncAccept, tcpListener); 

.......

void AsyncAccept(IAsyncResult ar) 
{ 
    var tcpListener = (TcpListener)ar.AsyncState; 
    var socket = tcpListener.EndAcceptSocket(ar); 
    if (ar.IsCompleted) 
    { 
     Console.WriteLine(socket.RemoteEndPoint + " connected..."); 
     var buf = new byte[0x10000]; 
     socket.BeginReceive(buf, 0, buf.Length, SocketFlags.None, AsyncRead, new Tuple<Socket, byte[]>(socket, buf)); 

     tcpListener.BeginAcceptSocket(AsyncAccept, tcpListener); 
    } 
} 

void AsyncRead(IAsyncResult ar) 
{ 
    var tuple = (Tuple<Socket, byte[]>)ar.AsyncState; 
    var socket = tuple.Item1; 
    var buf = tuple.Item2; 

    if (ar.IsCompleted) 
    { 
     var len = socket.EndReceive(ar); 
     var str = Encoding.UTF8.GetString(buf, 0, len); 
     Console.WriteLine(socket.RemoteEndPoint + ":" + str); 

     socket.BeginReceive(buf, 0, buf.Length, SocketFlags.None, AsyncRead, new Tuple<Socket, byte[]>(socket, buf)); 
    } 
}