how to create a chat console application in java using socket
Creating a chat console application in Java using sockets involves the following steps:
- Create a server program that listens for incoming client connections on a specified port.
- Create a client program that connects to the server on the specified port.
- Enable communication between the server and client programs.
Here's a basic implementation that you can use as a starting point:
Server Program:
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(8080); System.out.println("Server started"); Socket clientSocket = serverSocket.accept(); System.out.println("Client connected"); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); while (true) { String input = in.readLine(); if (input == null || input.equals("exit")) { break; } System.out.println("Client: " + input); String response = "Server: " + input.toUpperCase(); out.println(response); } System.out.println("Client disconnected"); serverSocket.close(); } }
Client Program:
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("localhost", 8080); System.out.println("Connected to server"); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter(socket.getOutputStream(), true); BufferedReader consoleIn = new BufferedReader(new InputStreamReader(System.in)); while (true) { String input = consoleIn.readLine(); out.println(input); if (input.equals("exit")) { break; } String response = in.readLine(); System.out.println(response); } System.out.println("Disconnected from server"); socket.close(); } }
In this example, the server listens for incoming client connections on port 8080. When a client connects, it creates a BufferedReader
and PrintWriter
to communicate with the client. The server reads input from the client, prints it to the console, and sends a response back to the client. The server stops when the client sends the "exit" message.
The client program connects to the server on port 8080, and creates a BufferedReader
and PrintWriter
to communicate with the server. The client reads input from the console, sends it to the server, and prints the response from the server. The client stops when the user types "exit".
To run the programs, start the server program first, then start one or more instances of the client program.