How to: Create a Socket Listener

.NET Framework 3.5

The .NET Compact Framework supports socket-based network communications. For considerations that are specific to programming sockets in the .NET Compact Framework, see Socket Programming.

This example creates an instance of a server application and an instance of a client application, and demonstrates how the two applications communicate over a socket-based connection. The localhost address is used for the server; therefore, both applications run on the client. An instance of the server must be running before the client can communicate with it.

To communicate over a socket connection

  1. Create a class named Server that implements Form, and add the following code to the class:

    static string output = "";
    
    public Server()
    {
    }
    
    public void createListener()
    {
        // Create an instance of the TcpListener class.
        TcpListener tcpListener = null;
        IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
        try
        {
            // Set the listener on the local IP address 
            // and specify the port.
            tcpListener = new TcpListener(ipAddress, 13);
            tcpListener.Start();
            output = "Waiting for a connection...";
        }
        catch (Exception e)
        {
            output = "Error: " + e.ToString();
            MessageBox.Show(output);
        }
        while (true)
        {
            // Always use a Sleep call in a while(true) loop 
            // to avoid locking up your CPU.
            Thread.Sleep(10);
            // Create a TCP socket. 
            // If you ran this server on the desktop, you could use 
            // Socket socket = tcpListener.AcceptSocket() 
            // for greater flexibility.
            TcpClient tcpClient = tcpListener.AcceptTcpClient();
            // Read the data stream from the client. 
            byte[] bytes = new byte[256];
            NetworkStream stream = tcpClient.GetStream();
            stream.Read(bytes, 0, bytes.Length);
            SocketHelper helper = new SocketHelper();
            helper.processMsg(tcpClient, stream, bytes);
        }
    }
    
    static void Main()
    {
        Application.Run(new Server());
    }
    
  2. In the Server class, provide a way to start the server. For example, call createListener in a button's Click event.

    private void button1_Click(object sender, EventArgs e)
    {
        this.createListener();
    }
    
  3. Create a class named SocketHelper, and add the following code to the class:

    class SocketHelper
    {
        TcpClient mscClient;
        string mstrMessage;
        string mstrResponse;
        byte[] bytesSent;
        public void processMsg(TcpClient client, NetworkStream stream, byte[] bytesReceived)
        {
            // Handle the message received and  
            // send a response back to the client.
            mstrMessage = Encoding.ASCII.GetString(bytesReceived, 0, bytesReceived.Length);
            mscClient = client;
            mstrMessage = mstrMessage.Substring(0, 5);
            if (mstrMessage.Equals("Hello"))
            {
                mstrResponse = "Goodbye";
            }
            else
            {
                mstrResponse = "What?";
            }
            bytesSent = Encoding.ASCII.GetBytes(mstrResponse);
            stream.Write(bytesSent, 0, bytesSent.Length);
        }
    }
    

    The server instantiates this class when a client connects to it.

  4. Create a class named Client that implements Form, and add the following code to the class:

    	public Client()
            {
                this.MinimizeBox = false;
            }
    
    	static void Connect(string serverIP, string message)
            {
                string output = "";
    
                try
                {
                    // Create a TcpClient. 
                    // The client requires a TcpServer that is connected 
                    // to the same address specified by the server and port 
                    // combination.
                    Int32 port = 13;
                    TcpClient client = new TcpClient(serverIP, port);
    
                    // Translate the passed message into ASCII and store it as a byte array.
                    Byte[] data = new Byte[256];
                    data = System.Text.Encoding.ASCII.GetBytes(message);
    
                    // Get a client stream for reading and writing. 
                    // Stream stream = client.GetStream();
                    NetworkStream stream = client.GetStream();
    
                    // Send the message to the connected TcpServer. 
                    stream.Write(data, 0, data.Length);
    
                    output = "Sent: " + message;
                    MessageBox.Show(output);
    
                    // Buffer to store the response bytes.
                    data = new Byte[256];
    
                    // String to store the response ASCII representation.
                    String responseData = String.Empty;
    
                    // Read the first batch of the TcpServer response bytes.
                    Int32 bytes = stream.Read(data, 0, data.Length);
                    responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
                    output = "Received: " + responseData;
                    MessageBox.Show(output);
    
                    // Close everything.
                    stream.Close();
                    client.Close();
                }
                catch (ArgumentNullException e)
                {
                    output = "ArgumentNullException: " + e;
                    MessageBox.Show(output);
                }
                catch (SocketException e)
                {
                    output = "SocketException: " + e.ToString();
                    MessageBox.Show(output);
                }
            }
    
    	static void Main()
            {
                Application.Run(new Client());
            }
    
  5. In the Client class, provide a way for the user to connect to the server. For example, call the Connect method in a button's Click event.

    private void button1_Click(object sender, EventArgs e)
    {
        // In this code example, use a hard-coded 
        // IP address and message. 
        string serverIP = "localhost";
        string message = "Hello";
        Connect(serverIP, message);
    }
    
  6. Compile the server and client applications.

  7. Deploy both applications to the device.

  8. Run the server application on the device, and start the server.

  9. Run the client application on the device, and connect to the server.

Community Additions

ADD
Show: