Answer to Question #232069 in Java | JSP | JSF for Rajib

Question #232069
Implement simple system using Socket Programming Sockets). your chat system includes two types of components i) A chat room and a) ii) The client b) System contains maximum 3 clients, each can enter or leave the system at any time and one can design GUI as given in Figure. c) server side. d) All messages are to be broadcasted to all clients connected to the chat room.
1
Expert's answer
2021-09-02T04:01:41-0400
import java.io.*;
import java.net.*;
import java.util.*;


public class ChatServer {
    private int pt;
    private Set<String> names = new HashSet<>();
    private Set<UserThread> userThreads = new HashSet<>();
 
    public ChatServer(int pt) {
        this.pt = pt;
    }
 
    public void execute() {
        try (ServerSocket serverSocket = new ServerSocket(pt)) {
 
            System.out.println("listening on port " + pt);
 
            while (true) {
                Socket s = serverSocket.accept();
                System.out.println("New user connected");
 
                UserThread newUser = new UserThread(s, this);
                userThreads.add(newUser);
                newUser.start();
 
            }
 
        } catch (IOException ex) {
            System.out.println("Error in the server: " + ex.getMessage());
            ex.printStackTrace();
        }
    }
 
    public static void main(String[] args) {
        if (args.length < 1) {
            System.out.println("Syntax: java ChatServer <port-number>");
            System.exit(0);
        }
 
        int pt = Integer.parseInt(args[0]);
 
        ChatServer server = new ChatServer(pt);
        server.execute();
    }
    void broadcast(String message, UserThread excludeUser) {
        for (UserThread aUser : userThreads) {
            if (aUser != excludeUser) {
                aUser.sendMessage(message);
            }
        }
    }
 
    void addUserName(String userName) {
        names.add(userName);
    }
 
    void removeUser(String userName, UserThread aUser) {
        boolean removed = names.remove(userName);
        if (removed) {
            userThreads.remove(aUser);
            System.out.println("The user " + userName + " quitted");
        }
    }
 
    Set<String> getUserNames() {
        return this.names;
    }
 
    boolean hasUsers() {
        return !this.names.isEmpty();
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS