0

当我在运行服务器后运行客户端时,服务器会因错误连接重置而崩溃......这是我的代码:

启动客户端套接字并连接到服务器。等待输入。客户:

    private Socket socket;
private BufferedReader in;
private PrintWriter out;
private String fromServer,fromUser;

public ClientTest() {
    try {
        socket = new Socket("127.0.0.1", 25565);
        out = new PrintWriter(socket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public void start() {
    try {
        while ((fromServer = in.readLine()) != null) {
            System.out.println(fromServer);
            out.println("1");
        }
        System.out.println("CLOSING");
        out.close();
        in.close();
        socket.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public static void main(String[] args) {
    new ClientTest();
}

启动服务器套接字并向客户端发送“2”并启动对话

服务器:

    public ServerTest() {
    try {
        serverSocket = new ServerSocket(25565);
        clientSocket = serverSocket.accept();

    } 
    catch (IOException e) {
        System.out.println("Could not listen on port: 4444");
        System.exit(-1);
    }
    start();
}

public void start() {

    try {
        PrintWriter out;
        out = new PrintWriter(clientSocket.getOutputStream(), true);
        BufferedReader in;
        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        String inputLine, outputLine;
        // initiate conversation with client
        out.println("2");
            while ((inputLine = in.readLine()) != null) {   
                System.out.println(inputLine);
                out.println("2");
            }
        System.out.println("Stopping");
        out.close();
        in.close();
        clientSocket.close();
        serverSocket.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

public static void main(String[] args) {
    new ServerTest();
}

当我运行服务器时,一切都很好,但是当我运行客户端之后,服务器因连接重置错误而崩溃。

4

2 回答 2

1

ClientTest() 不调用 start() 方法。您的客户端在建立连接后立即退出。

于 2012-05-16T10:11:20.433 回答
1

亚历克斯的回答是对的。

该程序也进入无限循环。您需要在客户端和服务器的while循环中添加退出条件。

于 2012-05-16T11:09:14.180 回答