void AuthenticateClientAndServer(bool server, bool client) { ClientServerState state = new ClientServerState(); state.Client = new TcpClient(); state.Listener = NetworkHelpers.CreateAndStartTcpListener(IPAddress.Loopback, out IPEndPoint endPoint); state.ServerAuthenticated = new AutoResetEvent(false); state.ClientAuthenticated = new AutoResetEvent(false); state.ServerIOException = !server; try { Thread serverThread = new Thread(() => StartServerAndAuthenticate(state)); serverThread.Start(); Thread clientThread = new Thread(() => StartClientAndAuthenticate(state, endPoint)); clientThread.Start(); Assert.AreEqual(server, state.ServerAuthenticated.WaitOne(TimeSpan.FromSeconds(5)), "server not authenticated"); Assert.AreEqual(client, state.ClientAuthenticated.WaitOne(TimeSpan.FromSeconds(5)), "client not authenticated"); } finally { if (state.ClientStream != null) { state.ClientStream.Dispose(); } state.Client.Close(); if (state.ServerStream != null) { state.ServerStream.Dispose(); } if (state.ServerClient != null) { state.ServerClient.Close(); } state.Listener.Stop(); } }
public void EndAcceptTcpClient() { var listenerSocket = NetworkHelpers.CreateAndStartTcpListener(IPAddress.Any, out int port); listenerSocket.BeginAcceptTcpClient(new AsyncCallback(l => { listenerSocket.EndAcceptTcpClient(l); }), null); using (var outClient = new TcpClient("localhost", port)) { using (var stream = outClient.GetStream()) { stream.WriteByte(3); } } }