At the end of this tutorial you will be able to know how sockets can exchange messages.
1- Java Server
The java server initiates the connection and launches listening on a port and waits for incoming connections to accept. For example, the port number is 5000, the client sends a request to the server with the port number 5000. The server accepts the request and forwarded his information (IP address) to the client. Now connection is established and an exchange of messages can be done.Java has a java.net package that processes the network, we need only two classes:
- java.net.ServerSocket: accepts connections goings of clients.
- java.net.Socket: allows connection to the remote machine.
- Scanner: read keyboard input.
- BufferedReader: read the text received from the transmitter.
- PrintWriter: send the text entered.
ServerSocket serverSocket; Socket socket; Final BufferedReader in; final PrintWriter out; Final Scanner sc = new Scanner (System.in); try { serverSocket = new ServerSocket (5000); serverSocket.accept = (); out = new PrintWriter ( .getOutputStream ()); in = new BufferedReader (new InputStreamReader ( .getInputStream ())); String s; s = sc.next (); System.out.println (s); out.flush (); String receivedmessage; receivedmessage in.readLine = (); System.out.println ("Client:" + receivedmessage); } catch (IOException e) { e.printStackTrace (); }
After creating the server socket that carries the port number 5000, the server waits for incoming connections and as soon as one is found, he accepts it. in and out are initialized so that they are directly connected with the sending and receiving streams.
Variable 's' stores the entered text with the next() method, and then sent to the println (s) method.
The flush() method is important because it flushes the write buffer to the output if a null value will be received by the other side.
The receivedmessage variable stores the received message is displayed with println() method.
The limit of this code is that it is able to send and receive a message once. You will have an idea in the head: to make a while loop (true). This is true, but if for example the server sends to the client, the client can not retrieve the message until it has sent also. The optimal solution is to create two threads: one for sending and one for receiving. Both processes allow the sending and receiving are done simultaneously.
java.io.BufferedReader import; import java.io.IOException; java.io.InputStreamReader import; java.io.PrintWriter import; java.net.ServerSocket import; java.net.Socket import; java.util.Scanner import; / * * javaisback.blogspot.com * / public class Server { public static void main (String [] test) { ServerSocket final serverSocket; Socket final clientSocket; Final BufferedReader in; final PrintWriter out; Final Scanner sc = new Scanner (System.in); try { serverSocket = new ServerSocket (5000); clientSocket serverSocket.accept = (); out = new PrintWriter (clientSocket.getOutputStream ()); in = new BufferedReader (new InputStreamReader (clientSocket.getInputStream ())); Thread sending = new Thread (new Runnable () { String msg; Override public void run () { while (true) { sc.nextLine msg = (); System.out.println (msg); out.flush (); } } }); envoi.start (); Thread receive = new Thread (new Runnable () { String msg; Override public void run () { try { in.readLine msg = (); // As the client is connected while (msg! = null) { System.out.println ("Client:" + msg); in.readLine msg = (); } // Exit the loop if the client connection is ended System.out.println ("Client deconected"); // Close the stream and socket session out.close (); clientSocket.close (); serverSocket.close (); } Catch (IOException e) { e.printStackTrace (); } } }); receive.start (); } Catch (IOException e) { e.printStackTrace (); } } }
The separation of the two processes is clear, the Server and the Client can exchange data at any time and infinitely. The while loop reading tests if the connection is not yet established if not forget to close your streams reading and writing as well as the connection after the exit of the while loop with close() method.
2- Java Client
The client side needs only the Socket class to establish the server connection, the constructor takes as input the server IP address and port number. The rest of the code is the same as that of the server.java.io.BufferedReader import; import java.io.IOException; java.io.InputStreamReader import; java.io.PrintWriter import; java.net.Socket import; java.util.Scanner import; / * * javaisback.blogspot.com * / public class Client{ public static void main (String [] args) { Socket final clientSocket; Final BufferedReader in; final PrintWriter out; Final Scanner sc = new Scanner (System.in); // to read from the keyboard try { / * * Server informations (port and IP address or host name * 127.0.0.1 is the host local address * / clientSocket = new Socket ("127.0.0.1", 5000); // Flow to send out = new PrintWriter (clientSocket.getOutputStream ()); // Feed to receive in = new BufferedReader (new InputStreamReader (clientSocket.getInputStream ())); Thread send = new Thread (new Runnable () { String msg; Override public void run () { while (true) { sc.nextLine msg = (); System.out.println (msg); out.flush (); } } }); send.start (); Thread receive = new Thread (new Runnable () { String msg; Override public void run () { try { in.readLine msg = (); while (msg! = null) { System.out.println ("Server:" + msg); in.readLine msg = (); } System.out.println ("Server deconected"); out.close (); clientSocket.close (); } Catch (IOException e) { e.printStackTrace (); } } }); receive.start (); } Catch (IOException e) { e.printStackTrace (); } } }
Output:
Server |
Client |
Cool, I take some "Insides" from here!
ReplyDeleteThanks a lot!
great
ReplyDeletewhat about multiple client can you help
ReplyDeleteAppreciating the persistence you put into your blog and detailed information you provide
ReplyDeletePython Online certification training
python Training institute in Chennai
Python training institute in Bangalore
Nice tutorial. Thanks for sharing the valuable information. it’s really helpful. Who want to learn this blog most helpful. Keep sharing on updated tutorials…
ReplyDeleteAWS Training in pune
AWS Online Training
Thanks For Sharing The Information The information shared Is Very Valuable Please Keep Updating Us Time just went On reading The article Python Online Training Aws Online Training Hadoop Online Training Data Science Online Training
ReplyDeleteWonderful to visit your websites, This sites are fully filled with full of Information's. I perceived a lots of knowledge from this Articles.
ReplyDeleteFor more to learn about Python Visit below
python training in chennai | python training in annanagar | python training in omr | python training in porur | python training in tambaram | python training in velachery
This is a nice article here with some useful tips for those who are not used-to comment that frequently.
ReplyDeleteThanks for this helpful information I agree with all points you have given to us.keep i up!!
android training in chennai
android online training in chennai
android training in bangalore
android training in hyderabad
android Training in coimbatore
android training
android online training
Such a very useful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article.
ReplyDeletehardware and networking training in chennai
hardware and networking training in velachery
xamarin training in chennai
xamarin training in velachery
ios training in chennai
ios training in velachery
iot training in chennai
iot training in velachery