gpt4 book ai didi

java - Java Socket为什么服务器无法回复客户端

转载 作者:行者123 更新时间:2023-12-03 11:58:15 24 4
gpt4 key购买 nike

我想编写代码,让客户端将字符串发送到服务器,服务器打印该字符串并回复一个字符串,然后客户端打印该字符串服务器回复。
我的服务器

public class Server {

public static void main(String[] args) throws IOException {
ServerSocket ss = null;
Socket s = null;
try {
ss = new ServerSocket(34000);
s = ss.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(
s.getInputStream()));
OutputStreamWriter out = new OutputStreamWriter(s.getOutputStream());

while (true) {
String string = in.readLine();
if (string != null) {
System.out.println("br: " + string);

if (string.equals("end")) {
out.write("to end");
out.flush();
out.close();
System.out.println("end");
// break;
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
s.close();
ss.close();
}
}
}

我的客户:
public class Client {
public static void main(String[] args) {
Socket socket =null;


try {
socket = new Socket("localhost", 34000);
BufferedReader in =new BufferedReader(new InputStreamReader(socket.getInputStream()));
OutputStreamWriter out = new OutputStreamWriter(socket.getOutputStream());

String string = "";
string = "end";
out.write(string);
out.flush();
while(true){
String string2 = in.readLine();
if(string2.equals("to end")){
System.out.println("yes sir");
break;
}
}


} catch (Exception e) {
e.printStackTrace();
}finally{
try {
System.out.println("closed client");
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}
}

有什么问题吗?如果我在客户端类中删除代码“while(true)...”,就可以了。

最佳答案

您应该在写入流的String的末尾添加"\r\n"

例子:

客户 :

    string = "end";
out.write(string + "\r\n");
out.flush();

服务器 :
    out.write("to end" + "\r\n");
out.flush();
out.close();
System.out.println("end");
// break;

关于java - Java Socket为什么服务器无法回复客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19489320/

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