gpt4 book ai didi

java - 如何使用 Java 套接字读取远程服务器的响应

转载 作者:行者123 更新时间:2023-12-01 15:12:43 25 4
gpt4 key购买 nike

我正在创建的 Java 程序的一部分需要与远程计算机上的服务进行通信。该远程计算机正在 Windows 平台上运行一个服务(我相信是用 Delphi 编写的)。

我需要连接到该机器,发送命令字符串并接收(字符串)响应。

如果我使用 Linux CLI telnet session 进行连接,我会得到预期的响应:

[dafoot@bigfoot ~]$ telnet [host IP] [host port]
Trying [host IP]...
Connected to [host IP].
Escape character is '^]'.
Welcome to MidWare server
ping
200 OK
ProcessDownload 4
200 OK

上面的行“ping”和“ProcessDownload 4”是我在终端中输入的,其他行是来自远程系统的响应。

我在我的 Java 类中创建了一个 Main 类,它将调用适当的方法来尝试测试它(我省略了不相关的内容):

public class DownloadService {
Socket _socket = null; // socket representing connecton to remote machine
PrintWriter _send = null; // write to this to send data to remote server
BufferedReader _receive = null; // response from remote server will end up here


public DownloadServiceImpl() {
this.init();
}

public void init() {
int remoteSocketNumber = 1234;
try {
_socket = new Socket("1.2.3.4", remoteSocketNumber);
} catch (IOException e) {
e.printStackTrace();
}
if(_socket !=null) {
try {
_send = new PrintWriter(_socket.getOutputStream(), true);
_receive = new BufferedReader(new InputStreamReader(_socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
}
public boolean reprocessDownload(int downloadId) {
String response = null;
this.sendCommandToProcessingEngine("Logon", null);
this.sendCommandToProcessingEngine("ping", null);
this.sendCommandToProcessingEngine("ProcessDownload", Integer.toString(downloadId));
try {
_socket.close();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
private String sendCommandToProcessingEngine(String command, String param) {
String response = null;
if(!_socket.isConnected()) {
this.init();
}
System.out.println("send '"+command+"("+param+")'");
_send.write(command+" "+param);
try {
response = _receive.readLine();
System.out.println(command+"("+param+"):"+response);
return response;
} catch (IOException e2) {
e2.printStackTrace();
}
return response;
}
public static void main(String[] args) {
DownloadServiceImpl service = new DownloadServiceImpl();
service.reprocessDownload(0);
}


}

正如您将在代码中看到的,有几个 sys.outs 来指示程序何时尝试发送/接收数据。

生成的输出:

send 'Logon(null)'
Logon(null):Welcome to MidWare server
send 'ping(null)'

因此 Java 正在连接到服务器,可以返回“欢迎使用中间件”消息,但是当我尝试发送命令(“ping”)时,我没有得到响应。

所以问题是:- Java 看起来正确吗?- 问题可能与字符编码有关(Java -> windows)吗?

最佳答案

您需要刷新输出流:

_send.write(command+" "+param+"\n"); // Don't forget new line here!
_send.flush();

或者,因为您创建了自动刷新PrintWriter:

_send.println(command+" "+param);

后者的缺点是行尾可以是 \n\r\n,具体取决于运行 Java VM 的系统。所以我更喜欢第一个解决方案。

关于java - 如何使用 Java 套接字读取远程服务器的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12107060/

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