我正在研究Java项目,其主要目的是允许用户彼此聊天。当前版本就像一个聊天室,每个人都可以编写并查看其他人发送的内容。我需要更改此设置,因此用户必须选择他正在写的对象,这意味着仅向其收件人显示消息。我的问题在这里:
public class Server {
private int port;
public static List<PrintStream> klienci;
private ServerSocket server;
public static void main(String[] args) throws IOException {
new Server(4444).run();
}
public Server(int port) {
this.port = port;
this.klienci = new ArrayList<PrintStream>();
}
public void run() throws IOException {
server = new ServerSocket(port) {
protected void finalize() throws IOException {
this.close();
}
};
System.out.println("Port 4444 works.");
while (true) {
Socket client = server.accept();
System.out.println("Connected " + client.getInetAddress().getHostAddress());
this.klienci.add(new PrintStream(client.getOutputStream()));
new Thread(new KLIENT(this, client.getInputStream())).start();
}
}
void MESSIN(String msg) {
for (PrintStream client : this.klienci) {
client.println(msg);
}
}
}
class KLIENT implements Runnable {
private Server server;
private InputStream client;
public KLIENT(Server server, InputStream client) {
this.server = server;
this.client = client;
}
public void run() {
String msg;
Scanner sc = new Scanner(this.client);
while (sc.hasNextLine()) {
msg = sc.nextLine();
server.MESSIN(msg);
}
sc.close();
}
}
我正在尝试在MESSIN中添加IF条件,但是我不知道如何通过其昵称来区分客户端(昵称是第二类,即Client,我不能使用它们)。