我刚刚创建了一个允许多个客户端之间通信的 Java 聊天应用程序,但是,我还希望一个客户端能够向特定客户端发送消息,其他客户端无法看到消息发送,就像一位客户对另一位客户窃窃私语。先感谢您。
这是我客户的一部分
public void sendListener(){
writer.println(clientName2+" : "+broadcastTF.getText() );
writer.flush();
broadcastTF.setText("");
broadcastTF.requestFocus();
}
public class listenServer implements Runnable{
public void run(){
try{
String text;
while((text = reader.nextLine()) != null){
messageTA.append(text+ "\n");
}
}catch(Exception ex){}
}
}
private void setupServer(){
try{
socket = new Socket("127.0.0.1", 7894);
writer = new PrintWriter(socket.getOutputStream());
reader = new Scanner(socket.getInputStream());
listenServer ls = new listenServer();
Thread t = new Thread(ls);
t.start();
}
catch(Exception ex){
}
}
这是我服务器的一部分
public class listenToClient implements Runnable{
Scanner reader;
public listenToClient(Socket socket){
try{
reader = new Scanner(socket.getInputStream());
}catch (Exception ex){}
}
public void run(){
try{
String text;
while((text = reader.nextLine()) != null){
sendToAll(text);
}
}catch(Exception ex){}
}
public void sendToAll(String text){
for (PrintWriter w : writers){
try{
w.println(text);
w.flush();
}catch(Exception ex){}
}
}
}