.Net Hive

A blog about Microsoft .Net Platform & other industry happenings

Socket / Network Programming in C#

Today I have decided to give a quick tutorial on Sockets/Network programming in C#. For this I have taken an example of a simple Client/Server application scenario. Where a Socket listen on a specific port and waits for the client to be connected. Once the client is connected, The client application will send a test message to the server application. I will try to achieve this functionality using minimal code and to give a concept of how socket programming works.

Hope this will be helpful. Following is the server application code.

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;

class SocketServer
{
  public static void Main()
  {
    StreamWriter streamWriter;
    StreamReader streamReader;
    NetworkStream networkStream;
    TcpListener tcpListener = new TcpListener(3333);
    tcpListener.Start();
    Console.WriteLine("Server Started. Waiting for Client Connection at port 3333");
    Socket serverSocket = tcpListener.AcceptSocket();
    try
    {
        if (serverSocket.Connected)
        {
            while (true)
            {
                Console.WriteLine("Client Connected at port 3333");
                networkStream = new NetworkStream(serverSocket);
                streamWriter = new StreamWriter(networkStream);
                streamReader = new StreamReader(networkStream);
                Console.WriteLine(streamReader.ReadLine());

            }
        }
        if (serverSocket.Connected)
            serverSocket.Close();
        Console.Read();
    }
    catch (SocketException ex)
    {
        Console.WriteLine(ex);
    }
  }
}

When the above code is executed, it will try to listen on port 3333 and will wait for an incoming connection from a client application. Upon start, server application will display a message “Server Started. Waiting for Client Connection at port 3333”. As soon as the server application recives the connection from client application, it show the message “Client Connected at port 3333”.

Now let’s see how our client application code looks like. Our client application will try to connect at port 3333. Following is the Client Application Code:

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;

class SocketClient
{
  static void Main(string[]args)
  {
    TcpClient tcpClient;
    NetworkStream networkStream;
    StreamReader streamReader;
    StreamWriter streamWriter;
    try
    {
        tcpClient = new TcpClient("localhost", 3333);
        networkStream = tcpClient.GetStream();
        streamReader = new StreamReader(networkStream);
        streamWriter = new StreamWriter(networkStream);
        streamWriter.WriteLine("Client connected at port 3333");
        streamWriter.Flush();
    }
    catch (SocketException ex)
    {
        Console.WriteLine(ex);
    }
    Console.Read();
  }
}

When the above client application code will execute, it will look for an opened connection from a server application at port 3333. As soon as it finds the connection, it will establish the connection with it and will send a message “Client connected at port 3333”. This test message will be displayed on server application console.

A Port is an integer that identifies a process running over a network for the purpose of providing a service. A socket is the end point of a two way communication between two processes running over a network. Microsoft .NET provides excellent support for writing programs that leverage the power of Sockets to implement programs that can run over a network to communicate and share data and information. 

In this entry we tried look at how we can work with Sockets using Microsoft .NET and how we can implement a simple client-server program that can communicate over a network. 

Your comments and suggestions are welcome.

Happy reading!

Waqas Ahmed

Filed under: .Net, Code Snippets, , ,

Pages

Categories

Archives

.Net Hive @ Twitter

Blog Directory by Blog Flux
Computers/Tech blogs