Proc
Proc
Eclipse, you need to create two programs: a server program and a client program.
Both can run on the same machine or different machines.
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 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.*;
// Close connections
clientSocket.close();
serverSocket.close();
System.out.println("Server disconnected.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.*;
import java.net.*;
// Close connection
socket.close();
System.out.println("Connection closed.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Explanation of the Code:
Server Side (ChatServer.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.