私が作成している 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.out がいくつかあります。
生成された出力:
send 'Logon(null)'
Logon(null):Welcome to MidWare server
send 'ping(null)'
したがって、Java はサーバーに接続して「Welcome to Midware」メッセージを返すことができますが、コマンド (「ping」) を送信しようとしても応答がありません。
質問: - Java は正しいように見えますか? - 問題は文字エンコーディング (Java -> Windows) に関連している可能性がありますか?