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

Java Client Server (Socket Programming) Tutorial

Introduction

This tutorial is aimed for programmers with at least a little experience with Java. For introductory material on Java, check out Sun's Java Tutorial and Java Documentation, which can be accessed from Sun's Java home page. Information on how to compile and run programs is also available there    

A socket is one end-point of a two-way communication link between two programs running on the network. These two programs form a Client/Server application.
In Client/Server applications the server normally listens to a specific port waiting for connection requests from a client. When a connection request arrives, the client and the server establish a dedicated connection over which they can communicate. During the connection process, the client is assigned a local port number, and binds a socket to it. The client talks to the server by writing to the socket and gets information from the server by reading from it. Similarly, the server gets a new local port number to communicate with the client. The server also binds a socket to its local port and communicates with the client by reading from and writing to it. The server can not use its specific port to comunicate with the client since it is dedicated only to listen for connection requests from other clients.

There are two communication protocols that one can use for socket programming: stream communication and dram communication.
The stream communication protocol is known as TCP (transfer control protocol). Unlike UDP, TCP is a connection-oriented protocol. In order to do communication over the TCP protocol, a connection must first be established between the pair of sockets. While one of the sockets listens for a connection request (server), the other asks for a connection (client). Once two sockets have been connected, they can be used to transmit data in both (or either one of the) directions.

The datagram communication protocol, known as UDP (user datagram protocol), is a connectionless protocol, meaning that each time you send datagrams, you also need to send the local socket descriptor and the receiving socket's address. As you can tell, additional data must be sent each time a communication is made.

UDP is an unreliable protocol, there is no guarantee that datagrams you have sent will be received in the same order by the receiving socket. On the other hand, TCP is a reliable protocol; it is guaranteed that the packets you send will be received in the order in which they were sent.

TCP is useful for implementing network services, such as remote login (rlogin, telnet) and file transfer (FTP) -- which require data of indefinite length to be transferred. UDP is less complex and is often used in implementing client/server applications in distributed systems built over local area networks.

This document we will show how to program sockets in Java using the TCP/IP protocol.

Client-Server-System
 A client server system is a system in which one system (the server) provides services for another (the client).
The two systems usually reside on different computers, perhaps on different continents.
Although, the constraints of the course computing arrangements dictate that most of our examples will be tested in setups in which the client and server reside on the same machine, the software we produce could be used without change in the distributed setting.

The goal of this discussion is to pair down the requirements for a client/server pair of applications to the bare essentials to illustrate establishing a connection between two processes running on different host machines. We'll discuss the server, first, and then a client that connects to an instance of this server that is already running.


Here is the server code:


package javaclientservercodeblogger;

import java.net.*;
import java.io.*;
import java.util.*;

public class Server extends Thread {

    /*Server port, clients list <ArrayList>*/
    
    private final int port = 7777;
    
    private ServerSocket ss;
    
    private ArrayList<clientThread> clients = new ArrayList();

    public Server() {
        try {
            
            /* Starting server on host and port */
            
            System.out.println("\nStarting server.. on port: " + port);
            ss = new ServerSocket(port);
            System.out.println("\nServer started..");

        } catch (IOException e) {
            System.out.println(e);
        }
    }

    public void run() {
        try {
            while (true) {
                /* Here is waiting for the clients */
                System.out.println("\nWaiting for a client...");
                addClient(); /* Accepting the clients which wants to connect. */
            }
        } catch (IOException e) {
            System.out.println(e);
        }
    }

    public synchronized void handle(int ID, String input) throws IOException{ 
        
        /* Reading the client messages*/
        
        System.out.println("\nMessage from client: "+input);
        
        /* If the client message is equals with HELLO SERVER, 
        the server will responds with HELLO CLIENT.*/
        
        if(input.equals("HELLO SERVER"))
        {
            clients.get(findClient(ID)).send("HELLO CLIENT!");
        }
    }
    public void addClient() throws IOException {
        clientThread client = new clientThread(this, ss.accept());
        client.open(); /* opening client streams*/
        client.start();
        clients.add(client); /* Addig client to the clients list <ArrayList>*/
        System.out.println("\nClient accepted.");
        client.send(">> WELCOME CLIENT! ");

    }

    /* Removing the client */
    public void removeClient(int ID) {
        clients.remove(findClient(ID));
        System.out.println("\nA Client was removed");
    }
/* Finding client position in the clients list*/
    public int findClient(int ID) {
        for (int i = 0; i < clients.size(); i+) {
            if (clients.get(i).ID == ID) {
                return i;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        new Server().start();
        new Client("localhost", 7777).start();
    }
    
} 

Client Thread code:

import java.io.*;
import java.net.*;

public class Client extends Thread {

    private Socket s;
    private DataInputStream in;
    private DataOutputStream out;

    public Client(final String host, final int port) {

        /* Attempting to connect */
        
        try {
            System.out.println("Connecting to host: " + host + " on " + port);
            s = new Socket(host, port);
            if(s.isConnected)
            {
                /* If is connected, will open the streams and sending the welcome message to the server. */
                
                open();
                System.out.println("Connecting to host: " + host + " on " + port);
                send("HELLO SERVER");
            }
            
        } catch (IOException e) {
            /* Connect problem.. */
            System.out.println("Can't connect to host. " + e.getMessage());
        }
    }

    public void run() {
        try {
            while (true) {
                /* Reading the server messages. */
                String message = in.readUTF();
                System.out.println("Message from server: "+message);
            }
        } catch (IOException e) {
            /* Reading problems, disconnect. */
            close();
            System.out.println("Disconnected. " + e.getMessage());
        }
    }

    public void open() throws IOException {
        
        /* Opening IO streams, after socket is connect.*/
        
        in = new DataInputStream(s.getInputStream());
        out = new DataOutputStream(s.getOutputStream());
    }

    public void close() {
        /* Closing the client streams. */
        try {
            out.close();
            in.close();
            s.close();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

    /* Sending message to the server. */
    public void send(String msg) throws IOException {
        out.writeUTF(msg);
    }
}
http://dwsdev.info check out our android applications.
Thank You for reading my post. You can download the source code here.


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.