Server is an application that runs on the host computer that provides a means of connection and useful information once a connection is established. Client is an application(s) running on different computer(s) that seek to establish a connection and request computation/ information from the server.

What is a Socket?

A socket is a communication end point. It is used by a process to communicate with a remote system via a transport protocol. It needs an IP address and a port number. Sockets are popularly used in client/server computing. Socket is a door between application process and end-to-end-transport protocol. A socket on one computer can “talk” to a socket on another computer via communication channel. Two main types of sockets supported in Java

  • TCP sockets (implemented by the Socket class)
  • UDP sockets (implemented by the DatagramSocket class)

TCP sockets are generally more commonly used and simpler.

At this point, some common facts are explained below that you must know before going into the details of TCP and UDP sockets.

Host

The Ip address of the machine we want to talk to.

Port number

  • A number identifying a process on the host.
  • This address is subdivided into 65,536 ports
  • Many services run on well-known ports. For example, http tends to run on port 80

Internet addresses

  • Every host on the Internet is identified by a unique, four-byte Internet Protocol (IP) address.
  • This is written in dotted format like 199.1.32.90 where each byte is an unsigned integer between 0 and 255.
  • There are about four billion unique IP addresses, but they aren’t very efficiently allocated

TCP Sockets

TCP is a reliable point-to-point communication protocol that client-server applications on the Internet use to communicate with each other. To communicate over TCP, a client program and a server program establish a connection to one another. The client and server programs both bind a socket to each end of the connection and communicate by reading and writing to those sockets. There are some commonly used socket classes in the java.net package.

Java uses Socket class for clients and ServerSocket class for servers in a connection-oriented environment

Client Sockets

To create client sockets java uses Socket class. This class has following two constructors:

  • Socket()
  • Socket(String host, int port)

Server Sockets

Life cycles of the client/server model

Life cycle of a client:

  1. A client socket is created using Socket()
  2. The socket connects to a remote host
  3. Data exchange between local and remote hosts.
    • an input stream to read data
    • an output stream to send data to server.
  4. Connection terminates after transmission of data is complete.

Life cycle of a server:

  1. A server socket is created on a particular port using ServerSocket().
  2. The socket listens for an incoming connection request from a client on the port using accept().
  3. Data exchange after connection is made.
    • The server and client interact according to an agreed upon protocol.
  4. Either or both of getInputStream() and getOutputStream(), depending on the type of server, is called to exchange data with the client.
  5. The server, the client, or both closes the connection upon completion of data exchange.
  6. The server returns to step 2 and waits for the next connection request.

Example: Java client (TCP)

import java.io.*;
import java.net.*;
class TCPClient {
    public static void main(String argv[]) throws Exception
    {
        String sentence;
        String modifiedSentence;
        BufferedReader inFromUser =
          new BufferedReader(new InputStreamReader(System.in));
        Socket clientSocket = new Socket("hostname", 6789);
        DataOutputStream outToServer =
          new DataOutputStream(clientSocket.getOutputStream());

        BufferedReader inFromServer =
          new BufferedReader(new
          InputStreamReader(clientSocket.getInputStream()));
        sentence = inFromUser.readLine();
        outToServer.writeBytes(sentence + '\n');
        modifiedSentence = inFromServer.readLine();
        System.out.println("FROM SERVER: " + modifiedSentence);
        clientSocket.close();

    }
}

Example: Java server (TCP)

import java.io.*;
import java.net.*;
class TCPServer {
  public static void main(String argv[]) throws Exception
    {
      String clientSentence;
      String capitalizedSentence;
      ServerSocket welcomeSocket = new ServerSocket(6789);

      while(true) {

            Socket connectionSocket = welcomeSocket.accept();
           BufferedReader inFromClient =
              new BufferedReader(new
              InputStreamReader(connectionSocket.getInputStream()));
           DataOutputStream  outToClient =
             new DataOutputStream(connectionSocket.getOutputStream());
           clientSentence = inFromClient.readLine();
           capitalizedSentence = clientSentence.toUpperCase() + '\n';
           outToClient.writeBytes(capitalizedSentence);
        }
    }
}

Multithreaded Server

The multithreaded server program creates a new thread for every client request. This way each client has its own connection to the server for passing data back and forth.

Basic Flow

The basic flow of logic of the multithreaded server can be summarized in a loop like given below:

while (true) {
         accept a connection ;
         create a thread to deal with the client ;
        end while
}

Multithreaded Server side code:

public class serverside {
	ServerSocket    server;
	static JTextArea    textArea;
public serverside(){
    listenSocket();     //method that accepts the connection and creates the client
}
public static void main(String argv[]) throws Exception {
      JFrame frame=new JFrame();
      textArea=new JTextArea();
	frame.add(textArea);
	frame.setSize(300,300);
	frame.setVisible(true);
       serverside ss=new serverside();
   }
public void listenSocket()
{ 	try{
	 server = new ServerSocket(4444); }
	catch (IOException e){
		 System.out.println("Could not listen on port 4444");
	   	 System.exit(-1); }
	while(true){
		ClientWorker w;
                System.out.println("server is listening for connection");
                textArea.append("server listening");
		try{	 //server.accept returns a client connection
 			w = new ClientWorker(server.accept(), textArea);
			Thread t = new Thread(w);
			 t.start();   }
		 catch (IOException e) {
		 	System.out.println("Accept failed: 4444"); System.exit(-1); }
 }
 }//end of listenSocket method
class ClientWorker implements Runnable
{ 	private Socket clientcon;
 	private JTextArea textArea;
ClientWorker(Socket client, JTextArea textArea) {
		this.clientcon = client;
		this.textArea = textArea;
	}
public void run(){
	String line;	BufferedReader   in = null; 	PrintWriter   out = null;
	try{
	 	in = new BufferedReader(new InputStreamReader(clientcon.getInputStream()));
		out = new PrintWriter(clientcon.getOutputStream(), true);
	} 	catch (IOException e) {
		 System.out.println("in or out failed"); System.exit(-1); }
      while(true){
	try{
		line = in.readLine();
		textArea.append(line); //Append 	data to text area
	}catch (IOException e) {
		 System.out.println("Read failed");
		System.exit(-1); 	} }}}

Client side code:

public class clientside implements ActionListener
{	Socket socket; 		PrintWriter out;		BufferedReader in;
	JButton bt;	JTextArea ta;
    public clientside(){
 	JFrame jf=new JFrame();
       bt=new JButton("send");
       ta=new JTextArea("write something to send");
       bt.addActionListener(this);
       jf.setLayout(new BorderLayout());
       jf.add(bt,BorderLayout.SOUTH);
       jf.add(ta,BorderLayout.CENTER);
       jf.setSize(300,300);
	 jf.setVisible(true);
        listenSocket();
	}
public static void main (String[] arg){
    clientside cs=new clientside();
    }
public void listenSocket(){
	//Create socket connection
   try{
  	socket = new Socket(“localhost", 4444);
     	out = new PrintWriter(socket.getOutputStream(), true);
     in = new BufferedReader(new InputStreamReader( socket.getInputStream()));
   }
	catch (UnknownHostException e) {
	     System.out.println("Unknown host: ");
	     System.exit(1);
   } catch  (IOException e) {
     System.out.println("No I/O");
     System.exit(1);
   }
}
public void actionPerformed(ActionEvent event){
   Object source = event.getSource();
   if(source == button){
   //Send data over socket
      String text = textField.getText();
      out.println(text);
      textField.setText(new String(""));
   }
}
socket.close();
}

The run method executes independently in each thread. If three clients request connections, three ClientWorker instances are created, a thread is started for each ClientWorker instance, and the run method executes for each thread. The JTextArea.append method is thread safe. If the JTextArea.append method were not thread safe.

public synchronized void appendText(line)
{
  textArea.append(line);
}

Tagged with: JAVAJAVA GUIObject OrientedProgrammingSource CodeThreads
 

5 Responses to Sockets and Network Programming in Java

  1. waqas says:

    Hi Sir in this code i got an error please help me.
    the error is:
    clientside.java:60: error: expected
    socket.close();
    ^
    1 error

    Waiting your Reply…

    • sourcecodemania says:

      There is a typing mistake in the code before this line.
      socket.close();

      I have corrected it. Run it now.

  2. Waza says:

    Hi ! I have some errors too :s

    1. There is an error at “socket.close();”, it’s not in a method…!

    2. “if(source == button)”, my IDE consider that “button” is a symbol, and it doesn’t find it :/

    See ya :)

  3. gustavo says:

    hellow can you tell me whats the error please i can make it run

  4. gopal says:

    Its work on same machine.not work on different machine.

    please tell me

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

 

Looking for something?

Use the form below to search the site:


Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Related News Feeds

Set your Twitter account name in your settings to use the TwitterBar Section.