gpt4 book ai didi

java - BufferedReader readLine 和 OutputStreamWriter .write

转载 作者:行者123 更新时间:2023-12-01 14:02:51 31 4
gpt4 key购买 nike

我有 2 个程序:客户端和服务器。

服务器创建一个 ServerSocket,客户端使用以下方式连接:

address = InetAddress.getByName(host);
conn = new Socket(address, port);

这是可行的,但问题是:void mousePressed() { 一旦单击鼠标就会被调用,执行以下命令:(客户端)

void mousePressed() {
try {
BufferedOutputStream os = new BufferedOutputStream(conn.getOutputStream());
OutputStreamWriter osw = new OutputStreamWriter(os, "US-ASCII");
osw.write("123");
osw.flush();
} catch (Exception e) {
e.printStackTrace();
}
}

服务器应该使用以下方式接收输入:

BufferedReader reader = new BufferedReader(
new InputStreamReader(new BufferedInputStream(conn.getInputStream())));
StringBuilder result = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
result.append(line);
}
reader.close();
println(result.toString());

服务器仅在客户端使用 conn.close(); 关闭套接字或退出客户端后才接收输入。由于我希望能够多次单击鼠标,因此无法关闭套接字。

如何在不关闭套接字的情况下发送输入?

编辑:连接代码:

服务器:

 // init
ServerSocket socket1;
int main_port = 5204;
// in main
try {
socket1 = new ServerSocket(main_port);
Socket conn = socket1.accept();
} catch (Exception e) {
e.printStackTrace();
}

客户:

// init
String host = "localhost";
int port = 5204;
Socket conn;
InetAddress address;
// in main
try {
address = InetAddress.getByName(host);
conn = new Socket(address, port);
} catch (Exception e) {
e.printStackTrace();
}

最佳答案

我的解决方案(基于其他答案和评论):

1) 在客户端中将 osw.write("123"); 更改为 osw.write("123\n");

2)更换

    BufferedReader reader = new BufferedReader(new InputStreamReader(new
BufferedInputStream(thread_cnn.getInputStream())));
StringBuilder result = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
result.append(line);
}
println(result);
reader.close();

BufferedReader reader = new BufferedReader(new InputStreamReader(new BufferedInputStream(conn.getInputStream())));        
String result = reader.readLine().toString();
println(result);
reader = null;
result = null;

在服务器上。

关于java - BufferedReader readLine 和 OutputStreamWriter .write,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19207276/

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