DaFoot
DaFoot

Reputation: 1567

How to read response from remote server using Java Sockets

Part of a Java program I'm creating needs to talk to a service on a remote machine. That remote machine is running a service (written in Delphi I believe) on a Windows platform.

I need to connect to that machine, send command strings and receive (String) responses.

If I connect using Linux CLI telnet session I get responses as expected:

[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 

In the above the lines 'ping' and 'ProcessDownload 4' are me typing in the terminal, other lines are responses from remote system.

I created a Main in my Java class that will do the work to call the appropriate methods to try and test this (I've left out irrelevant stuff):

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);
    }


}

As you will see in the code, there are a couple of sys.outs to indicate when the program is attempting to send/receive data.

The output generated:

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

So Java is connecting to the server ok to get the "Welcome to Midware" message back, but when I try to send a command ('ping') I don't get a response.

So the questions: - does the Java look about right? - could problem be related to character encoding (Java -> windows)?

Upvotes: 0

Views: 2769

Answers (1)

Aaron Digulla
Aaron Digulla

Reputation: 328584

You need to flush the output stream:

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

or, since you create a auto-flushing PrintWriter:

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

The latter has the disadvantage that the line end can be \n or \r\n, depending on the system on which your Java VM runs. So I prefer the first solution.

Upvotes: 1

Related Questions