gpt4 book ai didi

java - TCP程序中的问题(Java)

转载 作者:可可西里 更新时间:2023-11-01 02:31:39 25 4
gpt4 key购买 nike

谁能帮我调试这个程序?

服务器代码如下:

package networking;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

class TcpServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(5555);
while (true) {
Socket client = serverSocket.accept();
Scanner reader = new Scanner(client.getInputStream());
PrintWriter writer = new PrintWriter(client.getOutputStream());
String inputString = reader.nextLine();
System.out.println("Received from client : " + inputString);
writer.write(inputString.toUpperCase());
client.close();
}
}
}

这是客户端代码:

package networking;

import java.io.PrintWriter;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;

class TcpClient {
public static void main(String[] args) throws IOException {
Socket client = new Socket("localhost", 5555);
PrintWriter writer = new PrintWriter(client.getOutputStream());
Scanner reader=new Scanner(client.getInputStream());
writer.println("oPen SOurCe RUleS !");
System.out.println("Received from server : "+reader.nextLine());
client.close();
}
}

问题是,当我运行这个程序时,客户端和服务器都进入无限等待状态。谁能告诉我这段代码有什么问题吗?

提前致谢!

最佳答案

你试过了吗Flushing PrintWriter?

您关闭了流,但您从未通知作者您将要这样做。

关于java - TCP程序中的问题(Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1778106/

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