Ques: Use TCP Sockets to create a simple client-server based chat application. In the application, two clients connect to the same server and exchange messages between them. The server relays
these messages from one client to the other. Both the clients must have proper interfaces for sending and receiving chat messages.
these messages from one client to the other. Both the clients must have proper interfaces for sending and receiving chat messages.
Source Code:
Server:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(1998);
System.out.println("Waiting For Clients");
Socket clientone = serverSocket.accept();
System.out.println("Client One Connected");
Socket clienttwo = serverSocket.accept();
System.out.println("Client Two Connected");
new Thread(() -> {
try {
handle(clientone,clienttwo);
} catch (IOException e) {
e.printStackTrace();
}
}).start();
handle(clienttwo,clientone);
}
private static void handle(Socket clientone, Socket clienttwo) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(clientone.getInputStream()));
PrintWriter pr = new PrintWriter(clienttwo.getOutputStream());
while (true){
String x = br.readLine();
pr.println(x);
pr.flush();
}
}
}
Client:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("127.0.0.1",1998);
System.out.println("Connected To Server");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream());
new Thread(() -> {
try {
String msg = in.readLine();
System.out.println("Other : "+ msg);
} catch (IOException e) {
e.printStackTrace();
}
}).start();
while (true){
String msg = br.readLine();
out.println(msg);
out.flush();
System.out.println("You : "+msg);
}
}
}
Output:
Use TCP Sockets to create a simple client-server-based chat application. In the application, two clients connect to the same server and exchange messages between them. client server socket programming in java java socket client example socket programming in java source code udp client server program in java tutorial socket programming in java pdf chat application in java using socket programming how to get client port number in server socket programming in java client server socket programming in c
Comments