Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.0 kB
3
Indexable
Never
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

class TcpListenerExample
{
    static void Main(string[] args)
    {
        TcpListener server = null;
        try
        {
            // Set the TcpListener on port 5000
            Int32 port = 5000;
            IPAddress localAddr = IPAddress.Parse("192.168.1.100"); // Set the local IP address of the device
            server = new TcpListener(localAddr, port);

            // Start listening for client requests
            server.Start();

            // Buffer for reading data
            Byte[] bytes = new Byte[256];
            String data = null;

            // Enter the listening loop
            while (true)
            {
                Console.WriteLine("Waiting for a connection...");

                // Perform a blocking call to accept requests
                Socket socket = server.AcceptSocket();
                Console.WriteLine("Connected!");

                data = null;

                // Get a stream object for reading and writing
                NetworkStream stream = new NetworkStream(socket);

                int i;

                // Loop to receive all the data sent by the client
                while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                {
                    // Translate data bytes to a UTF8 string
                    data = Encoding.UTF8.GetString(bytes, 0, i);
                    Console.WriteLine("Received: {0}", data);
                }

                // Shutdown and end connection
                socket.Shutdown(SocketShutdown.Both);
                socket.Close();
            }
        }
        catch (SocketException e)
        {
            Console.WriteLine("SocketException: {0}", e);
        }
        finally
        {
            // Stop listening for new clients
            server.Stop();
        }

        Console.WriteLine("\nHit enter to continue...");
        Console.Read();
    }
}