我修改了 github 上的一个学校项目的开源项目来满足我的需求
它有一个 broadcast()
发送消息的方法,它在 run()
中被调用while 循环中的方法,但问题是 broadcast()
向 userList<>
中的所有用户发送消息我想添加通过写入 @username
向其中一个用户发送私有(private)消息的功能.
下面是广播方法的代码:
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)聊天功能,但它可以完美编译和运行。
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);}
最佳答案
我不知道你的程序是如何工作的,但你说程序运行完美,但不执行私有(private)消息传递部分。
如果我查看你的代码,在 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);
}
关于java - 无法使私有(private)广播方法起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51343290/