我有一个简单的服务器 - 多客户端程序,可以将用户的输入发送给每个人。 服务器获取消息,然后系统地将它们发送给每个人。
我遇到的问题是服务器获取消息,但在我与服务器断开连接之前不会发回消息。我为每个用户提供了一个线程,以及一个发送消息的线程。
这是主服务器:
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(25566);
SendThread SendThread = new SendThread();
new Thread(SendThread).start();
while(true){
Socket clientSocket = serverSocket.accept();
CollectThreads socketThread = new CollectThreads(clientSocket);
SendThread.Clients.add(socketThread);
new Thread(socketThread).start();
}
}
这是输入线程(CollectThreads):
public Socket Client;
public CollectThreads(Socket socket)
{
//Here we set the socket to a local variable so we can use it later
Client = socket;
}
@Override
public void run() {
System.out.println("i");
try{
PrintWriter out = new PrintWriter(Client.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(Client.getInputStream()));
out.println("Connected");
boolean x = true;
while(x){
String s;
if((s = in.readLine()) != null){
System.out.println(s);
SendThread.log.add(s);
}
}
} catch(IOException exception) {
System.out.println("Error: " + exception);
}
}
发件人(SendThread):
public ArrayList<CollectThreads> Clients = new ArrayList<CollectThreads>();
public static ArrayList<String> log = new ArrayList<String>();
@Override
public void run() {
try{
while(true){
String x;
while(!Clients.isEmpty()){
x = log.get(0);
for(int c = 0; c < Clients.size(); c += 1){
PrintWriter out = new PrintWriter(Clients.get(c).Client.getOutputStream(), true);
out.println(x);
System.out.println(x);
}
log.remove(0);
}
}
} catch(IOException exception) {
System.out.println("Error: " + exception);
}
}
如果我输入x,服务器控制台打印x,我断开连接,然后第二次打印x。 谁能找到我的错误?或者告诉我为什么这不起作用?
答案 0 :(得分:0)
你永远不会从SendThread.Clients中删除任何东西,所以我不明白为什么它不会无限期地重新发送同样的东西。
这是一个非常奇怪的设计。为什么不让每个客户端线程像其他人一样发送自己的输出?