gpt4 book ai didi

java - 无法从套接字的 InputStream 获取数据

转载 作者:行者123 更新时间:2023-11-29 03:46:14 25 4
gpt4 key购买 nike

尝试运行 echo 服务器时无法将数据读/写到套接字。没有抛出异常,也没有对控制台输入的响应。代码中有什么不正确的地方?

public class Server {

static ServerSocket server;

public static void main(String[] args) throws IOException {
String hostname = "127.0.0.1";

try{
server = new ServerSocket(8888);
} catch (IOException e) {
System.out.println("Could not listen on port 8888");
System.exit(-1);
}

Socket theSocket = null;
try {
theSocket = new Socket(hostname, 8888);

BufferedReader networkIn = new BufferedReader(new InputStreamReader(theSocket.getInputStream()));
BufferedReader userIn = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(theSocket.getOutputStream(), true);
System.out.println("Connected to echo server");

while (true) {
String theLine = userIn.readLine();
if (theLine.equals("."))
break;
out.println(theLine);
out.flush();
System.out.println("networkIn: "+networkIn.readLine());
}
networkIn.close();
out.close();
System.out.println("out.close();");
} catch (IOException e) {
e.printStackTrace();
}


}
}

最佳答案

您创建了两个不相关的套接字,一个用于接受连接,一个用于连接到 (hostname,8888)。您需要在服务器套接字上调用 accept() 才能真正连接到客户端。查看tutorial .

关于java - 无法从套接字的 InputStream 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10757792/

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