gpt4 book ai didi

java - 帮助第一个网络程序

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:36:29 24 4
gpt4 key购买 nike

这是代码。

public class testClient {
public static void main(String[] args) {
testClient abc = new testClient();
abc.go();
}
public void go() {
try {
Socket s = new Socket("127.0.0.1", 5000);
InputStreamReader sr = new InputStreamReader(s.getInputStream());
BufferedReader reader = new BufferedReader(sr);
String x = reader.readLine();
System.out.println(x);
reader.close();
} catch(IOException ex) {
ex.printStackTrace();
}
}
}

public class testServer {
public static void main(String[] args) {
testServer server = new testServer();
server.go();
}
public void go() {
try {
ServerSocket s = new ServerSocket(5000);
while(true) {
Socket sock = s.accept();

PrintWriter writer = new PrintWriter(sock.getOutputStream());
String toReturn = "No cake for you.";
writer.println(toReturn);
}
} catch(IOException ex) {
ex.printStackTrace();
}
}
}

java.io.*java.net.* 在两个类中导入。

现在,当我尝试运行这些(使用不同的终端)时,没有任何反应。我做错了什么?

屏幕:http://i29.tinypic.com/250qlmt.jpg

最佳答案

使用 PrintWriter 时需要调用 flush 方法。将您的代码更改为以下并且它有效:)。

public class testServer {
public static void main(String[] args) {
testServer server = new testServer();
server.go();
}
public void go() {
try {
ServerSocket s = new ServerSocket(5000);
while(true) {
Socket sock = s.accept();

PrintWriter writer = new PrintWriter(sock.getOutputStream());
String toReturn = "No cake for you.";
writer.println(toReturn);
writer.flush();
}
} catch(IOException ex) {
ex.printStackTrace();
}
}
}

关于java - 帮助第一个网络程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3381848/

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