[英]How to read response from remote server using Java Sockets
我正在创建的Java程序的一部分需要与远程计算机上的服务对话。 该远程计算机正在Windows平台上运行服务(我相信用Delphi编写)。
我需要连接到该计算机,发送命令字符串并接收(字符串)响应。
如果我使用Linux CLI telnet会话进行连接,则会得到预期的响应:
[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的系统。 所以我更喜欢第一个解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.