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