How to Implement Peer-to-Peer Communication in Java?
Peer-to-peer communication is a decentralized form of communication where two or more devices communicate directly with each other without the need for a central server. In peer-to-peer communication, each peer can act as both a client and a server, enabling them to both send and receive data.
Peer-to-Peer Communication in Java
Establishing peer-to-peer communication in Java can be achieved using various network communication protocols such as TCP/IP or UDP. Below are the following steps to implement peer-to-peer communication in Java.
- Create Socket Connections
- Server Setup
- Client Setup
- Data Exchange
Program to Peer to Peer Communication in Java
– Server
Below is the Program to implement the Server Side of Peer to Peer Communication in Java:
// Java Program to Implement Server Side
import java.io.*;
import java.net.*;
// Driver Class
public class Server {
// Main Function
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(12345);
System.out.println("Server started. Waiting for a client...");
// Wait for a client to connect
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected.");
// Open input and output streams
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
// Exchange data
String message = in.readLine();
System.out.println("Client: " + message);
out.println("Hello from server!");
// Close connections
in.close();
out.close();
clientSocket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
– Client
Below is the Program to implement the Client Side of Peer to Peer Communication in Java:
// Java Program to Implement Client Side
import java.io.*;
import java.net.*;
// Driver Class
public class Client {
// Main Function
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 12345);
System.out.println("Connected to server.");
// Open input and output streams
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
// Exchange data
out.println("Hello from client!");
String response = in.readLine();
System.out.println("Server: " + response);
// Close connections
in.close();
out.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output :
Connected to server.
Server: Hello from server!