【问题标题】:Client / Server application connection reset Java客户端/服务器应用程序连接重置 Java
【发布时间】:2012-05-16 09:30:24
【问题描述】:

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

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

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

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

【问题讨论】:

  • 你能添加你的堆栈跟踪吗?

标签: java networking client


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    Alex 的回答是对的。

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

    【讨论】:

    • 但它立即崩溃说连接重置我不认为它与无限循环有任何关系
    猜你喜欢
    • 2013-05-06
    • 1970-01-01
    • 2019-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多