0% found this document useful (0 votes)
3 views

Socket Programming

The document contains Java code for a simple chat application consisting of a ChatServer and a ChatClient. The server listens for client connections on port 12345 and facilitates message exchange until the client sends 'bye'. The client connects to the server, sends messages, and receives replies until it also sends 'bye'.

Uploaded by

Suhani Karki
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Socket Programming

The document contains Java code for a simple chat application consisting of a ChatServer and a ChatClient. The server listens for client connections on port 12345 and facilitates message exchange until the client sends 'bye'. The client connects to the server, sends messages, and receives replies until it also sends 'bye'.

Uploaded by

Suhani Karki
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Socket Programming

Design ChatServer
import java.io.*;

import java.net.*;

public class ChatServer {

public static void main(String[] args) {


try {

ServerSocket serverSocket = new ServerSocket(12345);


System.out.println("Server is waiting for a client...");

Socket socket = serverSocket.accept();

System.out.println("Client connected!");
BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader userInput = new BufferedReader(new
InputStreamReader(System.in));

String clientMessage;

while ((clientMessage = in.readLine()) != null) {


System.out.println("Client: " + clientMessage);
if (clientMessage.equalsIgnoreCase("bye")) break;
System.out.print("You: ");

String reply = userInput.readLine();


out.println(reply);

}
socket.close();
serverSocket.close();

} catch (IOException e) {
e.printStackTrace();

}
}

Design ChatClient
import java.io.*;

import java.net.*;

public class ChatClient {


public static void main(String[] args) {

try {

Socket socket = new Socket("localhost", 12345);

System.out.println("Connected to server!");
BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader userInput = new BufferedReader(new
InputStreamReader(System.in));

String message;
while (true) {

System.out.print("You: ");
message = userInput.readLine();
out.println(message);
if (message.equalsIgnoreCase("bye")) break;

String serverReply = in.readLine();


System.out.println("Server: " + serverReply);

socket.close();
} catch (IOException e) {
e.printStackTrace();

}
}

You might also like