gpt4 book ai didi

java - 写入行,读取行,然后关闭套接字

转载 作者:行者123 更新时间:2023-12-02 13:25:09 25 4
gpt4 key购买 nike

我需要从 Java 连接到 tcp/ip 套接字,以便执行一些操作:

1) 从套接字读取数据(可选的“hello”消息),然后丢弃它;

2) 将单行数据作为字符串写入套接字;

3) 从套接字读取响应(一行),并将其存储到字符串中;

4)关闭套接字;

我写了这段代码:

public String writeLineToSocket(String s) throws IOException {

Socket socket = null;
OutputStreamWriter osw = null;
BufferedReader is = null;
String response = null;

try {

socket = new Socket(serverAddress, serverPort);
is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
osw = new OutputStreamWriter(socket.getOutputStream(), "UTF-8");

osw.write(s, 0, s.length());
osw.flush();

response = is.readLine();
System.out.println(response);

} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket!=null) socket.close();
if (osw!=null) osw.close();
}

return response;
}

例如,使用 netcat dict.org 2628 我有第一条“你好”消息(我对此不感兴趣):

Linux 4.4.0-1-amd64 上的 220 pan.alephnull.com dictd 1.12.1/rf <42349519.9983.1492182590@pan.alephnull.com>

然后我想发送我的命令字符串:

定义wn java

最后我想将整个响应存储到一个字符串中:

150 1 definitions retrieved 151 "java" wn "WordNet (r) 3.0 (2006)" Java n 1: an island in Indonesia to the south of Borneo; one of the world's most densely populated regions 2: a beverage consisting of an infusion of ground coffee beans; "he ordered a cup of coffee" [syn: {coffee}, {java}] 3: a platform-independent object-oriented programming language . 250 ok [d/m/c = 1/0/14; 0.000r 0.000u 0.000s]

我的方法只显示 hello 消息,然后挂起......我做错了什么?

最佳答案

您的方法称为writeLine,但它不会写入一行,除非字符串已经有行终止符。添加一个。

关于java - 写入行,读取行,然后关闭套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43414323/

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