我这个是监听send按钮向所有客户端发送消息,请问怎样才能向指定客户端发送呢
public void actionPerformed(ActionEvent e) {
String data = "";
if ("sendMsg".equals(e.getActionCommand())) {
if ((data = this.input.getText()) != null) {
this.appendMsg("服务器-->" + data);
Set<Integer> keset = this.clients.keySet();
java.util.Iterator<Integer> iter = keset.iterator();
while (iter.hasNext()) {
int key = iter.next();
Socket socket = clients.get(key);
try {
Writer writer = new OutputStreamWriter(
socket.getOutputStream());
writer.write(ByteUtils.hexStr2Str(data.replace(" ", "")));
logger.debug(data);
writer.flush();
} catch (SocketException e1) {
} catch (IOException e1) {
e1.printStackTrace();
}
}
this.input.setText("");
}
}
}
key等于你指定的客户端时发消息,其它不处理
大佬,可以直接给代码吗
@阿飞滴滴滴:
public void actionPerformed(ActionEvent e) {
String data = "";
if ("sendMsg".equals(e.getActionCommand())) {
if ((data = this.input.getText()) != null) {
this.appendMsg("服务器-->" + data);
Set<Integer> keset = this.clients.keySet();
java.util.Iterator<Integer> iter = keset.iterator();
while (iter.hasNext()) {
int key = iter.next();
if (key == 你指定的客户端){
Socket socket = clients.get(key);
try {
Writer writer = new OutputStreamWriter(
socket.getOutputStream());
writer.write(ByteUtils.hexStr2Str(data.replace(" ", "")));
logger.debug(data);
writer.flush();
}
break;
}
......
@什麼江湖: 谢谢大佬,这块一直搞不懂
客户端的key 设置跟能区分是哪个客户端就可以。
谢谢大佬,上面已经解决了