Example #1
0
    public IEnumerator StartListening()
    {
        while (true)
        {
            // Set the event to nonsignaled state.
            _allDone = false;

            // Start an asynchronous socket to listen for connections.
            _ui.WriteLine("Waiting for a connection...");
            _socket.BeginAccept(AcceptCallback, state: _socket);

            // Wait until a connection is made before continuing.
            while (!_allDone)
            {
                yield return(null);
            }
        }
    }
Example #2
0
    private IEnumerator StartClient()
    {
        // Connect to a remote device.
        // Establish the remote endpoint for the socket.
        // The name of the
        // remote device is "host.contoso.com".
        IPHostEntry ipHostInfo = Dns.GetHostEntry(TCPTransfer.HOST_NAME);
        IPAddress   ipAddress  = ipHostInfo.AddressList[0];
        IPEndPoint  remoteEP   = new IPEndPoint(ipAddress, TCPTransfer.PORT);

        // Create a TCP/IP socket.
        Socket client = new Socket(ipAddress.AddressFamily,
                                   SocketType.Stream, ProtocolType.Tcp);

        // Connect to the remote endpoint.
        client.BeginConnect(remoteEP, ConnectCallback, client);
        while (!_connectDone)
        {
            yield return(null);
        }

        // Send test data to the remote device.
        Send(client, "This is a test<EOF>");
        while (!_sendDone)
        {
            yield return(null);
        }

        // Receive the response from the remote device.
        Receive(client);
        while (!_receiveDone)
        {
            yield return(null);
        }

        // Write the response to the console.
        _ui.WriteLine($"Response received : {_response}");

        // Release the socket.
        client.Shutdown(SocketShutdown.Both);
        client.Close();
    }
Example #3
0
    public TCPServer(TCPTransfer ui)
    {
        _ui = ui ?? throw new ArgumentNullException(nameof(ui));

        // Establish the local endpoint for the socket.
        // The DNS name of the computer
        // running the listener is "host.contoso.com".
        _ui.WriteLine($"StartListening() - host name: {Dns.GetHostName()}");

        IPHostEntry ipHostInfo    = Dns.GetHostEntry(Dns.GetHostName());
        IPAddress   ipAddress     = ipHostInfo.AddressList[0];
        IPEndPoint  localEndPoint = new IPEndPoint(ipAddress, TCPTransfer.PORT);

        // Create a TCP/IP socket.
        _socket = new Socket(ipAddress.AddressFamily,
                             SocketType.Stream, ProtocolType.Tcp);

        // Bind the socket to the local endpoint and listen for incoming connections.

        _socket.Bind(localEndPoint);
        _socket.Listen(100);
    }