【发布时间】:2019-04-03 23:02:08
【问题描述】:
所以我有一个家庭作业,要在一台服务器上创建 2 个客户端在一台服务器上进行通信。客户端 1 和客户端 2 可以与服务器通信,但我需要 2 个客户端与每个客户端进行通信,我被难住了??
我很确定我在正确的轨道上使用 ArrayList 添加客户端并使用 for 循环遍历它们。我只是不知道如何连接 t 个客户端以相互通信。 这是我的代码。
//通信线程类在Server.class文件中。 while true 循环中的 for 循环应该让 2 个客户端进行通信,但不是吗??
class ComThreads implements Runnable{
private Socket s;
java.util.Date date=new java.util.Date();
public ComThreads(Socket s)
{
this.s=s;
}
public void run()
{ try {
DataInputStream inputFromClient = new DataInputStream(
s.getInputStream());
DataOutputStream outputToClient = new DataOutputStream(
s.getOutputStream());
while(true) {
String line=inputFromClient.readUTF();
for(int i=0; i < clientList.size(); i++) {
if(clientList.get(i).equals(s)) {
Socket tempSoc=clientList.get(i);
DataOutputStream msOut=new DataOutputStream(tempSoc.getOutputStream());
msOut.writeUTF(line);
//outputToClient.writeUTF(message);
msOut.flush();
}
}
Platform.runLater(()->{
ta.appendText(line);
ta.appendText("\n");
});
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
s.close();
}catch(IOException e) {
// later
}
}
}
}
}
只需要 2 个客户端进行通信。任何帮助,将不胜感激。 谢谢
【问题讨论】:
-
我没有遵循代码。请发帖minimal reproducible example。我假设 2 个客户端通过服务器进行通信。
标签: java multithreading sockets datainputstream dataoutputstream