2010. október 25., hétfő

Csharp Client Server (Socket Programming) Tutorial

USING C# .NET SOCKET PROGRAMMING



Sockets are an important part of the modern programmer's armory. I will show an example below.


The term client-server refers to a popular model for computer networking that utilizes client and server devices each designed for specific purposes. The client-server model can be used on the Internet as well as local area networks (LANs). Examples of client-server systems on the Internet include Web browsers and Web servers, FTP clients and servers, and DNS.



Client/server describes the relationship between two computer programs in which one program, the client, makes a service request from another program, the server, which fulfills the request. Although the client/server idea can be used by programs within a single computer, it is a more important idea in a network. In a network, the client/server model provides a convenient way to interconnect programs that are distributed efficiently across different locations. Computer transactions using the client/server model are very common. For example, to check your bank account from your computer, a client program in your computer forwards your request to a server program at the bank. That program may in turn forward the request to its own client program that sends a request to a database server at another bank computer to retrieve your account balance. The balance is returned back to the bank data client, which in turn serves it back to the client in your personal computer, which displays the information for you.
The client/server model has become one of the central ideas of network computing. Most business applications being written today use the client/server model. So does the Internet's main program, TCP/IP. 

Client-server is just one approach to managing network applications The primary alternative, peer-to-peer networking, models all devices as having equivalent capability rather than specialized client or server roles. Compared to client-server, peer to peer networks offer some advantages such as more flexibility in growing the system to handle large number of clients. Client-server networks generally offer advantages in keeping data secure.




What Is a Socket?

A socket is one end-point of a two-way communication link between two programs running on the network. Socket classes are used to represent the connection between a client program and a server program. The java.net package provides two classes--Socket and ServerSocket--that implement the client side of the connection and the server side of the connection, respectively.

Reading from and Writing to a Socket

This page contains a small example that illustrates how a client program can read from and write to a socket.

Writing a Client/Server Pair










/* Server code. */

    class Server
    {
        /* The server will start on this host and port. */

        string ip = "127.0.0.1";

        int port = 7777;

        TcpListener tcpLsn;

        Socket newClient;

        /* Setting up the buffer size 32k */

        byte[] buffer = new byte[32768];

         public Server()
        { 
             /* Here starts the server */

            try
            {
                tcpLsn = new TcpListener(System.Net.IPAddress.Parse(ip), port);

                tcpLsn.Start();

                Console.WriteLine("[SERVER] Server is started on host: " + ip + 
                " and port: " + port);

                Console.WriteLine("\nWaiting for clients...");

                /* Calling the method: WaitingForClient(), 
                which is reads from client's messages. */

                Thread tcpThd = new Thread(new ThreadStart(WaitingForClient));

                tcpThd.Start();
            }
            catch (SocketException se)
            {
                /* If couldn't start, will wrrite an error message on the console. */

                Console.WriteLine("Error when starting the server: "+se.Message);
            }
        }
        void WaitingForClient()
        {
            while (true)
            {
                /* If the client attempts to connect, 
                 the server socket will accept it. */

                newClient = tcpLsn.AcceptSocket;

                /* Calling the method: Read(), 
                which is reads the server's messages. */

                Thread readTread = new Thread(new ThreadStart(Read));

                readTread.Start();
            }
        }
        void Read()
        {
            try
            {
                int receivedDataLength = 
                newClient.Receive(buffer, SocketFlags.None);

                string message = 
                Encoding.ASCII.GetString(buffer, 0, receivedDataLength);

                /* Showing server messages. */

                Console.WriteLine("\nMessage from the client: " + message);

                /* If the client sends HELLO SERVER message to the server, 
                 * the server will responds with HELLO CLIENT. 
                 */
               
                if (message == "HELLO SERVER!")
                {
                    Send("HELLO CLIENT!");
                }
            }
            catch (Exception e)
            {
                /* Server reading problems. */

                Console.WriteLine(e.Message);
            }
        }
        void Send(string msg)
        {
            /* Sending the message to server. */

            buffer = Encoding.ASCII.GetBytes(msg);           

            newClient.Send(buffer, SocketFlags.None, null);
        }
    }

    /* The Client code. */





class Client
    {
        string ip = "127.0.0.1";

        int port = 7777;

        Socket s;

        byte[] buffer = new byte[32768];

        public Client()
        {
            IPAddress host = IPAddress.Parse(ip);

            IPEndPoint hostep = new IPEndPoint(host, port);

            /* Connecting to the server. */

            s = new Socket(AddressFamily.InterNetwork, 
            SocketType.Stream, ProtocolType.Tcp);

            s.Connect(hostep);

            if (s.Connected)
            {
                /* if the client is connected, 
                will show this information below, then call the Read() method. */

                Console.WriteLine("\n
                [CLIENT] We are connected to the server: " + ip +
                on port: " + port);

                Thread readTread = new Thread(new ThreadStart(Read));

                readTread.Start();

                /* Sending the welcome message to the server, 
                and the server will responds with HELLO CLIENT. */

                Send("HELLO SERVER!");
            }
        }

void Read()
        {
            while (true)
            {
                try
                {
                    /* Reading server messages. */

                    int receivedDataLength = s.Receive(buffer, SocketFlags.None);

                    string message = 
                    Encoding.ASCII.GetString(buffer, 0, receivedDataLength);

                    Console.WriteLine("\nMessage from the server: " + message);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
        }
        void Send(string msg)
        {
            /* Sending message to the server. */

            buffer = Encoding.ASCII.GetBytes(msg);

            s.Send(buffer);
        }
    }


http://dwsdev.info check out our android applications.




Thank You for reading this post.

You can download the source code here.