November 3, 2005

Socket Programming using .Net 2.0 System.Net.Socket

Socket is a communication mechanism where we use to connect client and the server. Basically the Server will listen to the client connections on specific port number. A client can connect to the Server by using the relevant hostname and the port number. Upon the successful client connection server will gets a new socket bound to a different port. It needs the original socket for listen to other client connections while communicating with the connected client. Below is the simple client /server example done using the .Net 2.0. Review the code & you will find it interesting. (I made it very simple to make you understand) You can modify the code to meet your needs.  

Server Code:

class MyServer
    {
        //Listing to the client connections.
        public void Listen()
        {
            byte[] ipArray = new byte[4];
            ipArray[0] = 127;
            ipArray[1] = 0;
            ipArray[2] = 0;
            ipArray[3] = 1;
            IPAddress add = new IPAddress(ipArray);
            //This is obselete in .Net 2.0
            //TcpListener tcpListener = new TcpListener(10);

            TcpListener tcpListener = new TcpListener(add, 10);
            tcpListener.Start();
            Socket socketForClient = tcpListener.AcceptSocket();
            if (socketForClient.Connected)
            {
                Util.Out("client connected..");
                NetworkStream netStream = new NetworkStream(socketForClient);
                StreamWriter writer = new StreamWriter(netStream);
                StreamReader reader = new StreamReader(netStream);
                string str = "Message from Server : " + DateTime.Now.ToLongDateString();
                writer.WriteLine(str);
                Util.Out("What meessage do you want to send to client?");
                writer.WriteLine(Console.ReadLine());
                writer.Flush();
                str = reader.ReadLine();
                Util.Out(str);
                reader.Close();
                writer.Close();
                netStream.Close();
            }
            socketForClient.Close();
            Util.Out("Exiting...");
        }
    }

Client Code :

public class MyClient
    {
        //Connects to the server
        public void Connect()
        {
            TcpClient socketForServer = null;
            try
            {
                socketForServer = new TcpClient("localhost", 10);
                Util.Out("Connected to the Server");
            }
            catch
            {
                Util.Out("Failed to connecto localhost");
                Util.Out("Exiting..");
                return;
            }
            NetworkStream netstream = socketForServer.GetStream();
            StreamReader reader = new StreamReader(netstream);
            StreamWriter writer = new StreamWriter(netstream);
            try
            {
                string output1, output2;
                output1 = reader.ReadLine();
                output2 = reader.ReadLine();
                Util.Out(output1);
                Util.Out(output2);
                writer.Flush();
                reader.Close();
            }
            catch
            {
                Util.Out("Exception Occured! Exiting...");
            }
            netstream.Close();
        }
    }

    This is small helper class…
    public class Util
    {
        public static void Out(string s)
        {
            Console.WriteLine(s);
        }
    }

This is a simple console application. You can create two console application one for the server & one for the client. Run the server first then client app. If you want you can create nice windows applications using this two simple classes to communicate over network.

3 comments:

Anonymous said...

Hi
if i want to archive this using asp.net then can I ?

Anonymous said...

Buona Sera! Charles Wilson . payday loans

Anonymous said...

cash advance toronto This website is optimal I enjoyed it a whole lot
AAA Toronto Payday Loans 1172 Bay St #101, Toronto, ON M5S 2B4 (416) 477-2817