gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 07:47:36 26 4
gpt4 key购买 nike

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

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

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

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

最佳答案

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

关于java - 客户端/服务器应用程序连接重置 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10615705/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com