1

我正在尝试为我的聊天程序创建一个服务器,但由于某种原因,它只需要输入,并且即使你一遍又一遍地按 enter 也会继续这样做。我试图仅在命令行中运行服务器,因此无法向服务器提供一些命令。有谁知道它为什么这样做?

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;


public class Server {

ArrayList<PrintWriter> clientOutputStreams;
int port;
ServerSocket serverSocket;

public class ClientHandler implements Runnable {
    BufferedReader reader;
    Socket socket;

    public ClientHandler(Socket clientSocket) {
        try {
            socket = clientSocket;
            InputStreamReader isReader = new InputStreamReader(socket.getInputStream());
            reader = new BufferedReader(isReader);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public void run() {
        String message;
        try {
            while ((message = reader.readLine()) != null) {
                tellEveryone(message);
                System.out.println(message);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

}

public static void main(String args[]) {
    new Server().go();

}

public void createSocket() {
    try {
        port = 31996;
        serverSocket = new ServerSocket(port);
    } catch (Exception e) {
        System.out.println("The port is in use or does not exist! Please pick an unused port between 1025 and 65535.");
        createSocket();
    }
}

public void go() {

    clientOutputStreams = new ArrayList<PrintWriter>();

    try {
        createSocket();
        while (true) {
            Socket clientSocket = serverSocket.accept();
            PrintWriter writer = new PrintWriter(
                    clientSocket.getOutputStream());
            clientOutputStreams.add(writer);

            Thread t = new Thread(new ClientHandler(clientSocket));
            t.start();
            System.out.println("Server started on port " + port+ ".");
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

public void tellEveryone(String message) {

    Iterator<PrintWriter> it = clientOutputStreams.iterator();
    while (it.hasNext()) {
        try {
            PrintWriter writer = (PrintWriter) it.next();
            writer.println(message);
            writer.flush();

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}

}

4

1 回答 1

0

我想这个条件while ((message = reader.readLine()) != null)永远不会满足。

您需要发送某种“终止”消息或让客户端关闭连接。

于 2012-09-27T02:58:09.807 回答