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.