Srikanth Technologies

Two-way Server and Client sockets using C#

Here is a Server socket that takes currency symbol and returns conversion rate to INR for the given symbol.

Server socket is implemented as a Console Application. It uses a dictionary object to store conversion rates to simplify the process. The client is a windows application that creates a client socket, which connects to server.

The focus of this example is to show how two-way communication between client and server sockets takes place.

Creating Server Socket - CurrencyServer

Follow the steps given below to create a console application for server socket.
  1. Create a new project using File->New Project.
  2. Select Visual C# as the language and select Console Application as the project type. Enter CurrencyServer as the name of the project.
  3. Enter the following code in Program.cs.
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Net.Sockets;
    
    namespace CurrencyServer
    {
        class Program
        {
            public static void Main()
            {
                Dictionary rates = new Dictionary(); 
                // put some sample data into dictionary object. Values are not accurate and important
                rates.Add("usd", 47.5); 
                rates.Add("eur", 60.4);
                rates.Add("ukp", 78.8);
    
                // create a server socket with port number 2000
                TcpListener l = new TcpListener(2000);
                l.Start();  // start listening for client requests
                Console.WriteLine("Server has started.Waiting for clients...");
                while (true)
                {
                    TcpClient c = l.AcceptTcpClient();  // wait and accept client request
                    Console.WriteLine("Opened connection with client..");
                    NetworkStream ns = c.GetStream(); // get stream to send and receive data
                    byte[] buf;
                    while (true)
                    {
                        buf = new byte[10];
                        ns.Read(buf, 0, 10); // read symbol from client
                        // convert bytes to string
                        string symbol = System.Text.Encoding.ASCII.GetString(buf);
                        symbol = symbol.Substring(0, 3); // take only first 3 characters
                        
                        if (symbol == "end") break;  // stop if symbol is "end"
                        
                        // find out the corresponding rate
                        byte[] result;
                        try
                        {
                            double value = rates[symbol];
                            result = System.Text.Encoding.ASCII.GetBytes(value.ToString());
                        }
                        catch (Exception ex)
                        {
                            result = System.Text.Encoding.ASCII.GetBytes("Invalid");
                            Console.WriteLine(ex);
                        }
                        ns.Write(result, 0, result.Length); // write rate or error message to client
                    }
                    // close connection
                    ns.Close();  
                    c.Close();
                    Console.WriteLine("Closed connection with client..");
                }
            }
        }
    }
    
    
The above program creates an object TcpListener (server socket) with port number 2000. It takes symbol from client and sends the corresponding conversion rate to client. The connection to client is closed when client sends “end” as the symbol to server.

Run Server Socket

Take the following steps to run server socket.
  1. Build the project using Build->Build Solution.
  2. Go to Command line.
  3. Go to project folder for CurrencyServer project.
  4. Run CurrencyServer.exe, which is in bin\debug folder inside the project folder.

Creating Client Socket - CurrencyClient

Client socket is created as a windows application. It allows user to select currency symbol and get the corresponding conversion rate from server socket.
  1. Create a new project using File->New Project.
  2. Select Visual C# and Windows Forms Application.
  3. Enter application name as CurrencyClient.
  4. Place the controls (as shown in the form below) on the form and change the required properties. For Combobox use Items property to enter currency symbols that we used in CurrencyServer.

    Write the following code to connect to server in the constructor and code for click events of buttons.

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.Net.Sockets;
    
    namespace CurrencyClient
    {
        public partial class Form1 : Form
        {
            TcpClient c = null;
            NetworkStream ns;
    
            public CurrencyClient()
            {
                InitializeComponent();
                
                // get connection to server
                c = new TcpClient("localhost", 2000);
                ns = c.GetStream();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                string symbol = ddlSymbols.SelectedItem.ToString();  // get selected symbol from combo box
                byte[] buf = System.Text.Encoding.ASCII.GetBytes(symbol);
                ns.Write(buf, 0, symbol.Length); // send symbol to server
                
                byte[] rate = new byte[100];
                ns.Read(rate, 0, 100);  // read data from server 
                
                lblRate.Text =  System.Text.Encoding.ASCII.GetString(rate);  // place rate or error message into Label
            }
    
            private void button2_Click(object sender, EventArgs e)
            {
                // send "end" to server so that connection to client is closed
                byte[] buf = System.Text.Encoding.ASCII.GetBytes("end"); 
                ns.Write(buf, 0, 3);
                this.Dispose(); // close form and application
            }
        }
    }
    
    
    Run the client application using F5 from Visual Studio. Select a symbol from drop down list and click on Get Rate button. Once done, click on Exit button to close client and connect to server.