无法使私有广播方法工作

u2nhd7ah  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(252)

我修改了github上的一个开源项目作为一个学校项目,以满足我的需要,它有一个 broadcast() 方法发送消息,并在 run() 方法,但问题是 broadcast() 将消息发送给 userList<> 我想添加一个功能,通过编写 @username .
以下是广播方法的代码:

private synchronized void broadcast(String msg) {
    for (int i = 0; i < clientList.size(); i++) {
        clientList.get(i).write(msg);
    }
    System.out.println("Log: Message broadcast --> " + msg);
}

下面是run()方法

public void run() {
    System.out.println("Log: Got input/output streams for connected client.");

    /**Get the first message from the client, attempt communication */
    String clientMsg = null;
    boolean accepted = false;

    /**Allow client to create an account, login, or quit */
    do {
        clientMsg = client.read();
        if (clientMsg.equals("QUIT")) {
            System.out.println("Log: Client disconnected without signing in.");
            client.disconnect();
            return;
        }
        else if (clientMsg.startsWith("NEWUSER: ")) {
            createUser(clientMsg);
        }
        else if (clientMsg.startsWith("LOGIN: ")) {
            accepted = authenticate(clientMsg);
        }
        else
        {
            System.out.println("Log: Unexpected client message -> " + clientMsg);
            client.disconnect();
            return;
        }
    } while(!accepted);

    /**Run main chat loop. Will read from the client, and broadcast each read
     *  until the client disconnects. */
    while (true) {
                int i=0;
                String username= clientList.get(i).getUsername();
        String line = client.read();
        if (line == null) break;
                    else if(line.startsWith("@"+username)){
                     broadcastp(line,username);
                    }
        else {

                        broadcast(line);

                    }
i++;
    }

    /**The only way for the client to exit the above loop is to disconnect.
     *  Therefore, call the handler's exit routine */
    exit();
}

这是你的名字 broadcastp() 方法,但它不起作用。它的编译和运行非常完美,尽管没有私人聊天功能。

private synchronized void broadcastp(String msg,String username) {
             for (int i = 0; i < clientList.size(); i++) {
        username = clientList.get(i).getUsername();
        if(msg.startsWith("@"+username))
        {clientList.get(i).write(msg);}
        else {
        continue;
        }}
    System.out.println("Log: Message broadcast --> " + msg);}
l5tcr1uw

l5tcr1uw1#

我不知道你的程序是如何工作的,但是你说这个程序运行得很好,但是没有做私人消息传递的部分。
如果我看看你的代码 while 循环您总是从 clientList ( i = 0 )只打电话 broadcastp 如果行以该名称开头。
首先。。是 broadcastp 曾经调用过吗?在 broadcastp 你有另一个循环,但它总是匹配的 i == 0 给定调用它的方式(使用 while 循环)。
问题似乎就在那里。因此while循环中的类似内容可能对您有用(删除 i 变量,不需要 broadcastp ):

boolean isPrivate = false;
String line = client.read();

for (User user : clientList) {
    if (line.startsWith("@" + user.getUsername())) {
        user.write(line);
        isPrivate = true;
        break;
    }
}

if (!isPrivate) {
    broadcast(line);
}

相关问题