Inte rnet Чат-сервер в java - PullRequest
       39

Inte rnet Чат-сервер в java

0 голосов
/ 17 июня 2020

Я разработал сервер / клиент для службы многостороннего чата Inte rnet (например, IR C) с использованием протокола TCP. Пользователи запускают клиентскую программу, которая подключается к серверу. Затем пользователи могут отправлять введенные пользовательские сообщения на этот сервер, который затем рассылает их другим клиентам. Входящие сообщения могут рассылаться напрямую (немедленно). Сервер также должен информировать все подключенные стороны, когда один из пользователей теряет соединение. Я разрешил двум пользователям создать частный канал чата, набрав @username. Мне нужна помощь, чтобы позволить одному из пользователей навсегда запретить другим пользователям дальнейшие разговоры, отправив в качестве примера (#username) на сервер. Я пробовал, но это не работает, пожалуйста, мне нужна помощь att эту реализацию. Ниже код на стороне сервера. Спасибо.

введите здесь код

public class Server {
private static int Id;

private ArrayList<ClientThread> arrlist;// an ArrayList to keep the list of the Client
private SimpleDateFormat sdf;// to display time
private int port;// the port number to listen for connection
private boolean running; // to check if server is running
public String Status;

//constructor that receive the port to listen to for connection as parameter

public Server(int port) {

    this.port = port;
    sdf = new SimpleDateFormat("HH:mm:ss");
    arrlist = new ArrayList<ClientThread>();
}

public void start() {
    running = true;
    //create socket server and wait for connection requests 
    try 
    {

        ServerSocket serverSocket = new ServerSocket(port);

        // infinite loop to wait for connections
        while(running) 
        {
            display("Server waiting for Clients on port " + port + ".");
            Socket socket = serverSocket.accept();  // accept connection 
            if(!running)
                break;
            ClientThread t = new ClientThread(socket);// create its thread
            arrlist.add(t);
            t.start();
        }

        try {
            serverSocket.close();
            for(int i = 0; i < arrlist.size(); ++i) {
                ClientThread tc = arrlist.get(i);
                try {
                // close all data streams and socket
                tc.sInput.close();
                tc.sOutput.close();
                tc.socket.close();
                }
                catch(IOException ioE) {
                }
            }
        }
        catch(Exception ex) {
            display("Exception closing the server and clients: " + ex);
        }
    }
    catch (IOException ex) {
        String msg = sdf.format(new Date()) + " Exception on new ServerSocket: " + ex + "\n";
        display(msg);
    }
}

// to stop the server
protected void stop() {
    running = false;
    try {
        new Socket("localhost", port);
    }
    catch(Exception e) {
    }
}

// Display an event to the console
private void display(String msg) {
    String time = sdf.format(new Date()) + " " + msg;
    System.out.println(time);
}

// to broadcast a message to all Clients
private synchronized boolean broadcast(String message) {

    String time = sdf.format(new Date());
    // to check if message is private client to client message
    String[] str = message.split(" ",3);
    boolean isBlocked = false;
    boolean isPrivate = false;

    if(str[1].charAt(0)=='#') 
        isBlocked =true;
    if(isBlocked==true) {................**I need help here please what should do here **..............}

    if(str[1].charAt(0)=='@') 
        isPrivate=true;
    // if private message, send message to mentioned user name only
    if(isPrivate==true)
    {
        String tocheck=str[1].substring(1, str[1].length());
        message=str[0]+str[2];
        String messageLf = time + " " + message + "\n";
        boolean found=false;
        // we loop in reverse order to find the mentioned username
        for(int y=arrlist.size(); --y>=0;)
        {
            ClientThread ct1=arrlist.get(y);
            String check=ct1.getUsername();
            if(check.equals(tocheck))
            {

                if(!ct1.writeMsg(messageLf)) {
                    arrlist.remove(y);
                    display("Disconnected Client " + ct1.username + " removed from list.");
                }

                found=true;
                break;
            }

            }

        if(found!=true)
        {
            return false; 
        }
    }
    // if message is a broadcast message
    else
    {
        String messageLf = time + " " + message + "\n";
        // display message
        System.out.print(messageLf);

        for(int i = arrlist.size(); --i >= 0;) {
            ClientThread ct = arrlist.get(i);
            // try to write to the Client if it fails remove it from the list
            if(!ct.writeMsg(messageLf)) {
                arrlist.remove(i);
                display("Disconnected Client " + ct.username + " removed from list.");
            }
        }

}
    return true;
    }   
...