To implement a simple chat application using TCP socket communication in Java using
Eclipse, you need to create two programs: a server program and a client program.
Both can run on the same machine or different machines.
Here's how you can do it:
Steps:
Create the Java Projects in Eclipse:
Open Eclipse and create two Java projects: one for the Server and one for the
Client.
Each project should contain a main class: ChatServer for the server and ChatClient
for the client.
Server Program (ChatServer.java):
The server listens for incoming client connections on a specific port.
It waits for messages from clients and can send responses back.
Client Program (ChatClient.java):
The client connects to the server using the server's IP address and port number.
It sends and receives messages to/from the server.
ChatServer.java (Server Code):
java
import java.io.*;
import java.net.*;
public class ChatServer {
public static void main(String[] args) {
try {
// Create server socket on port 1234
ServerSocket serverSocket = new ServerSocket(1234);
System.out.println("Server is waiting for a client connection...");
// Accept client connections
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " +
clientSocket.getInetAddress());
// Create input/output streams
BufferedReader clientInput = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
PrintWriter clientOutput = new
PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader consoleInput = new BufferedReader(new
InputStreamReader(System.in));
String clientMessage, serverMessage;
// Listen for client messages and send responses
while (true) {
// Read message from client
clientMessage = clientInput.readLine();
if (clientMessage == null ||
clientMessage.equalsIgnoreCase("exit")) {
break;
}
System.out.println("Client: " + clientMessage);
// Read server message from console
System.out.print("Server: ");
serverMessage = consoleInput.readLine();
// Send response to client
clientOutput.println(serverMessage);
}
// Close connections
clientSocket.close();
serverSocket.close();
System.out.println("Server disconnected.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
ChatClient.java (Client Code):
import java.io.*;
import java.net.*;
public class ChatClient {
public static void main(String[] args) {
try {
// Connect to the server at localhost and port 1234
Socket socket = new Socket("localhost", 1234);
// Create input/output streams
BufferedReader serverInput = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter serverOutput = new PrintWriter(socket.getOutputStream(),
true);
BufferedReader userInput = new BufferedReader(new
InputStreamReader(System.in));
String messageFromServer, messageToSend;
// Chat loop: exchange messages
while (true) {
// Read message from server
messageFromServer = serverInput.readLine();
if (messageFromServer != null) {
System.out.println("Server: " + messageFromServer);
}
// Read message from user
System.out.print("You: ");
messageToSend = userInput.readLine();
// Send message to server
serverOutput.println(messageToSend);
// Exit if user types "exit"
if (messageToSend.equalsIgnoreCase("exit")) {
break;
}
}
// Close connection
socket.close();
System.out.println("Connection closed.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Explanation of the Code:
Server Side (ChatServer.java):
The ServerSocket is created on port 1234.
The server listens for incoming client connections. When a client connects, a
Socket is created, and input/output streams are set up.
The server can send and receive messages in a loop, reading from the client and
writing to the client.
The loop ends if the message "exit" is received or if the connection is lost.
Client Side (ChatClient.java):
The client creates a Socket and connects to the server running at localhost on port
1234.
It has input/output streams to send and receive messages.
The client sends a message to the server, waits for a response, and prints it on
the console. The loop ends when the user types "exit".
Running the Application:
Start the Server:
First, run the ChatServer program. The server will wait for a client connection.
Start the Client:
Next, run the ChatClient program. The client will connect to the server.
Communication:
Once the client is connected, both programs can exchange messages.
Type "exit" in either the client or the server to terminate the connection.
Notes:
This program uses localhost for both client and server running on the same machine.
If the client and server are on different machines, you will need to replace
"localhost" with the server's IP address in the ChatClient code.
The server and client can also run in parallel on different machines by adjusting
the Socket connection to the appropriate IP address.