Socket Read and Write in Different Threads

Prerequisites : Socket Programming in Java

This article assumes that you have bones cognition of socket programming in java and the bones details of customer-server model used in advice.

Why to utilize threads in network programming?

The reason is simple, we don't want but a unmarried client to connect to server at a item time merely many clients simultaneously. We desire our architecture to support multiple clients at the same time. For this reason, nosotros must utilise threads on server side so that whenever a client request comes, a dissever thread can be assigned for treatment each request.

Let us take an example, suppose a Date-Time server is located at a place, say X. Being a generic server, it does not serve any detail customer, rather to a whole ready of generic clients. As well suppose at a detail time, two requests arrives at the server. With our basic server-client program, the request which comes fifty-fifty a nano-second first would be able to connect to the server and the other request would be rejected equally no mechanism is provided for handling multiple requests simultaneously. To overcome this trouble, we utilize threading in network programming.
The post-obit article will focus on creating a simple Date-Fourth dimension server for handling multiple customer requests at the same time.

Quick Overview

As normal, we volition create 2 java files,Server.java and Client.java. Server file contains 2 classes namely Server (public course for creating server) and ClientHandler (for handling any client using multithreading). Client file contain just one public class Client (for creating a client). Below is the flow diagram of how these three classes collaborate with each other.

Date-time-server-1

Server Side Programming(Server.coffee)

  • Server class : The steps involved on server side are similar to the article Socket Programming in Coffee with a slight change to create the thread object after obtaining the streams and port number.
    1. Establishing the Connection: Server socket object is initialized and within a while loop a socket object continuously accepts incoming connection.
    2. Obtaining the Streams: The inputstream object and outputstream object is extracted from the current requests' socket object.
    3. Creating a handler object: Later obtaining the streams and port number, a new clientHandler object (the in a higher place class) is created with these parameters.
    4. Invoking the starting time() method : The start() method is invoked on this newly created thread object.
  • ClientHandler grade : As we will be using dissever threads for each request, lets understand the working and implementation of the ClientHandler form extending Threads. An object of this form will exist instantiated each time a request comes.
    1. First of all this class extends Thread and then that its objects assumes all properties of Threads.
    2. Secondly, the constructor of this class takes iii parameters, which tin uniquely identify any incoming request, i.e. a Socket, a DataInputStream to read from and a DataOutputStream to write to. Whenever we receive whatsoever asking of customer, the server extracts its port number, the DataInputStream object and DataOutputStream object and creates a new thread object of this class and invokes start() method on it.
      Note : Every request will always have a triplet of socket, input stream and output stream. This ensures that each object of this course writes on one specific stream rather than on multiple streams.
    3. Inside the run() method of this class, information technology performs three operations: asking the user to specify whether time or date needed, read the answer from input stream object and appropriately write the output on the output stream object.

import java.io.*;

import java.text.*;

import java.util.*;

import java.net.*;

public form Server

{

public static void master(String[] args) throws IOException

{

ServerSocket ss = new ServerSocket( 5056 );

while ( true )

{

Socket due south = null ;

try

{

s = ss.have();

System.out.println( "A new client is connected : " + due south);

DataInputStream dis = new DataInputStream(s.getInputStream());

DataOutputStream dos = new DataOutputStream(s.getOutputStream());

System.out.println( "Assigning new thread for this client" );

Thread t = new ClientHandler(southward, dis, dos);

t.outset();

}

grab (Exception e){

s.close();

due east.printStackTrace();

}

}

}

}

class ClientHandler extends Thread

{

DateFormat fordate = new SimpleDateFormat( "yyyy/MM/dd" );

DateFormat fortime = new SimpleDateFormat( "hh:mm:ss" );

final DataInputStream dis;

terminal DataOutputStream dos;

last Socket s;

public ClientHandler(Socket south, DataInputStream dis, DataOutputStream dos)

{

this .south = s;

this .dis = dis;

this .dos = dos;

}

@Override

public void run()

{

String received;

String toreturn;

while ( true )

{

try {

dos.writeUTF( "What practice you want?[Date | Time]..\north" +

"Type Go out to stop connexion." );

received = dis.readUTF();

if (received.equals( "Exit" ))

{

System.out.println( "Client " + this .s + " sends leave..." );

System.out.println( "Closing this connection." );

this .s.close();

System.out.println( "Connection closed" );

break ;

}

Date engagement = new Date();

switch (received) {

case "Appointment" :

toreturn = fordate.format(date);

dos.writeUTF(toreturn);

pause ;

example "Fourth dimension" :

toreturn = fortime.format(appointment);

dos.writeUTF(toreturn);

suspension ;

default :

dos.writeUTF( "Invalid input" );

intermission ;

}

} catch (IOException e) {

eastward.printStackTrace();

}

}

endeavour

{

this .dis.close();

this .dos.close();

} catch (IOException e){

east.printStackTrace();

}

}

}

Output

A new customer is connected : Socket[addr=/127.0.0.ane,port=60536,localport=5056] Assigning new thread for this client Client Socket[addr=/127.0.0.1,port=60536,localport=5056] sends exit... Closing this connectedness. Connection closed        

Client Side Programming (Client.coffee)

Customer side programming is similar equally in general socket programming program with the post-obit steps-

  1. Establish a Socket Connexion
  2. Communication

import java.io.*;

import java.net.*;

import java.util.Scanner;

public class Client

{

public static void main(String[] args) throws IOException

{

try

{

Scanner scn = new Scanner(System.in);

InetAddress ip = InetAddress.getByName( "localhost" );

Socket s = new Socket(ip, 5056 );

DataInputStream dis = new DataInputStream(south.getInputStream());

DataOutputStream dos = new DataOutputStream(south.getOutputStream());

while ( true )

{

Arrangement.out.println(dis.readUTF());

String tosend = scn.nextLine();

dos.writeUTF(tosend);

if (tosend.equals( "Exit" ))

{

System.out.println( "Closing this connection : " + s);

s.close();

Arrangement.out.println( "Connexion airtight" );

pause ;

}

String received = dis.readUTF();

System.out.println(received);

}

scn.close();

dis.shut();

dos.close();

} catch (Exception e){

eastward.printStackTrace();

}

}

}

Output :

What practise you lot want?[Appointment | Time].. Blazon Exit to terminate connection. Date 2017/06/16 What practice you want?[Date | Fourth dimension].. Type Exit to stop connection. Time 05:35:28 What do you lot want?[Date | Fourth dimension].. Type Get out to end connectedness. Geeks Invalid input What do yous want?[Date | Fourth dimension].. Type Exit to terminate connection. Get out Closing this connection : Socket[addr=localhost/127.0.0.1,port=5056,localport=60536] Connexion closed        

How these programs works together?

  1. When a client, say client1 sends a asking to connect to server, the server assigns a new thread to handle this request. The newly assigned thread is given the access to streams for communicating with the client.
  2. Afterward assigning the new thread, the server via its while loop, again comes into accepting state.
  3. When a second request comes while first is nevertheless in procedure, the server accepts this requests and once again assigns a new thread for processing it. In this way, multiple requests tin be handled even when some requests are in process.

How to examination the in a higher place program on your system?

Save the ii programs in same packet or anywhere. Then showtime run the Server.coffee followed by the Client.java. You tin can either copy the client program in two three dissever files and run them individually, or if you take an IDE like eclipse, run multiple instances from the same program. The output shown above is from a single client plan, the similar results will exist achieved if multiple clients are used.

Next: Multi-threaded conversation Application : Server Side Programming , Client Side Programming

This commodity is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, yous can besides write an commodity using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your commodity actualization on the GeeksforGeeks main page and help other Geeks.

Please write comments if you notice annihilation incorrect, or you lot want to share more data about the topic discussed higher up.


ciprianiquisging.blogspot.com

Source: https://www.geeksforgeeks.org/introducing-threads-socket-programming-java/

0 Response to "Socket Read and Write in Different Threads"

إرسال تعليق

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel