0
我创建的Java程序的一部分需要与远程计算机上的服务对话。该远程计算机正在Windows平台上运行服务(用Delphi编写)。如何使用Java套接字从远程服务器读取响应
我需要连接到该机器,发送命令字符串并接收(字符串)响应。
如果我连接使用Linux CLI telnet会话我得到预期的反应:
[[email protected] ~]$ 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
在该行“平”和“ProcessDownload 4”我打字在终端上面,其他线路是从反应远程系统。
我创造了我的Java类主要是做这项工作,调用相应的方法来尝试和测试这个(我已经离开了无关紧要的东西):
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.out来指示程序何时试图发送/接收数据。
输出生成的:
send 'Logon(null)'
Logon(null):Welcome to MidWare server
send 'ping(null)'
所以Java被连接到服务器确定以“欢迎使用中间件”的消息,但是当我尝试发送一个命令(“中国平安”)我不得到回应。
所以问题: - Java看起来是否正确? - 问题可能与字符编码有关(Java - > windows)?
从服务器获得更有用的响应,而不是我期待的响应,但我现在正在得到响应。干杯。 – DaFoot