In this tutorial you will learn how to create a java chat between two hosts using sockets, as well as your network configuration in order to communicate two machines on the local network of your home for example. We will implement what we saw in theory: Client / Server model.
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.
We also need tools to capture, send and receive the stream:
- 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 |
If you work on the same machine you need to run Eclipse twice. one for the server and one for the client.