0% found this document useful (0 votes)
20 views6 pages

Simple Java Chat System Code

Uploaded by

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

Simple Java Chat System Code

Uploaded by

saadafriditv
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1

Programming Assignment Unit 7

University of People
2

SIMPLE CHAT SYSTEM:

[Link]:

import [Link].*;

import [Link].*;

import [Link].*;

public class ChatServer {

private static final int PORT = 12345;

private static Set<PrintWriter> clientWriters = new HashSet<>();

public static void main(String[] args) {

[Link]("Chat server started...");

try (ServerSocket serverSocket = new ServerSocket(PORT)) {

while (true) {

new ClientHandler([Link]()).start();

} catch (IOException e) {

[Link]();

private static class ClientHandler extends Thread {


3

private Socket socket;

private PrintWriter out;

private BufferedReader in;

public ClientHandler(Socket socket) {

[Link] = socket;

public void run() {

try {

in = new BufferedReader(new InputStreamReader([Link]()));

out = new PrintWriter([Link](), true);

synchronized (clientWriters) {

[Link](out);

String message;

while ((message = [Link]()) != null) {

[Link]("Received: " + message);

synchronized (clientWriters) {

for (PrintWriter writer : clientWriters) {

[Link](message);

}
4

} catch (IOException e) {

[Link]();

} finally {

try {

[Link]();

} catch (IOException e) {

[Link]();

synchronized (clientWriters) {

[Link](out);

[Link]:

import [Link].*;

import [Link].*;
5

public class ChatClient {

private static final String SERVER_ADDRESS = "localhost";

private static final int SERVER_PORT = 12345;

public static void main(String[] args) {

try (Socket socket = new Socket(SERVER_ADDRESS, SERVER_PORT);

BufferedReader userInput = new BufferedReader(new


InputStreamReader([Link]));

PrintWriter out = new PrintWriter([Link](), true);

BufferedReader in = new BufferedReader(new


InputStreamReader([Link]()))) {

[Link]("Connected to chat server.");

// Thread to read messages from server

new Thread(() -> {

try {

String message;

while ((message = [Link]()) != null) {

[Link]("Server: " + message);

} catch (IOException e) {
6

[Link]();

}).start();

// Read user input and send to server

String userMessage;

while ((userMessage = [Link]()) != null) {

[Link](userMessage);

} catch (IOException e) {

[Link]();

You might also like