客户/服务器应用程序连接重置Java

时间:2012-05-16 09:30:25

标签: java networking client

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

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

    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();
}

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

亚历克斯的答案是对的。

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