private void EndAccept(IAsyncResult result) { Socket peerSocket = null; try { Socket listener = (Socket)result.AsyncState; peerSocket = listener.EndAccept(result); IPEndPoint endpoint = (IPEndPoint)peerSocket.RemoteEndPoint; Uri uri = new Uri("ipv4://" + endpoint.Address.ToString() + ':' + endpoint.Port); Peer peer = new Peer("", uri, EncryptionTypes.All); IConnection connection = null; if (peerSocket.AddressFamily == AddressFamily.InterNetwork) { connection = new IPV4Connection(peerSocket, true); } else { connection = new IPV6Connection(peerSocket, true); } RaiseConnectionReceived(peer, connection, null); } catch (SocketException) { // Just dump the connection if (peerSocket != null) { peerSocket.Close(); } } catch (ObjectDisposedException) { // We've stopped listening } finally { try { if (Status == ListenerStatus.Listening) { listener.BeginAccept(endAcceptCallback, listener); } } catch (ObjectDisposedException) { } } }
void OnSocketReceived(object sender, SocketAsyncEventArgs e) { Socket socket = null; try { // Capture the socket (if any) and prepare the args for reuse // by ensuring AcceptSocket is null. socket = e.AcceptSocket; e.AcceptSocket = null; if (e.SocketError != SocketError.Success) { throw new SocketException((int)e.SocketError); } IConnection connection; if (socket.AddressFamily == AddressFamily.InterNetwork) { connection = new IPV4Connection(socket, true); } else { connection = new IPV6Connection(socket, true); } var peer = new Peer("", connection.Uri, EncryptionTypes.All); ConnectionReceived?.Invoke(this, new NewConnectionEventArgs(peer, connection, null)); } catch { socket?.Close(); } try { if (!((Socket)sender).AcceptAsync(e)) { OnSocketReceived(sender, e); } } catch { return; } }
void OnSocketReceived(object sender, SocketAsyncEventArgs e) { Socket socket = null; try { if (e.SocketError != SocketError.Success) { throw new SocketException((int)e.SocketError); } socket = e.AcceptSocket; // This is a crazy quirk of the API. We need to null this // out if we re-use the args. e.AcceptSocket = null; IConnection connection; if (socket.AddressFamily == AddressFamily.InterNetwork) { connection = new IPV4Connection(socket, true); } else { connection = new IPV6Connection(socket, true); } var peer = new Peer("", connection.Uri, EncryptionTypes.All); ConnectionReceived?.Invoke(this, new NewConnectionEventArgs(peer, connection, null)); } catch { socket?.Close(); } try { if (!((Socket)sender).AcceptAsync(e)) { OnSocketReceived(sender, e); } } catch { return; } }