Valter Silva
Valter Silva

Reputation: 16656

Java: How communicate with machines?

i'm trying to communicate with my device through java. I can communicate with it using telnet, i know that because i use PuTTY, so my configuration is:

ip: 192.168.1.4 port: 2001 communication type: telnet

This works, my device and network is working fine.

So i though that i could do the same through java, then i create this class:

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 *
 * @author Valter
 */

public class Middleware {

    public static void main(String args[]) {
        try {
            Socket socket = new Socket("192.168.1.4", 2001);

            // create a channel between to receive data
            DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());

            // create a channel between to send data
            DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());

            dataOutputStream.writeUTF("}Rv!");
//            dataOutputStream.flush();

            String answer= dataInputStream.readUTF();
            System.out.println("Answer:"+answer);

            dataInputStream.close();
            dataOutputStream.close();
            socket.close();

        } catch (UnknownHostException ex) {
            System.out.println("EXCEÇÃO UNKNOW HOST EXCEPTION");
        } catch (IOException ex) {
            System.out.println("EXCEÇÃO IOEXCEPTION");
            System.out.println(ex.getMessage());
        }
    }
}

But when i try to execute this, nothing happens, no exceptions, no nothing. I looks like a 'while' without end.

What should i do here? I should use a client telnet to java here?

Upvotes: 1

Views: 340

Answers (2)

jarnbjo
jarnbjo

Reputation: 34313

What do you really want to send to the device? DataOutputStream#writeUTF uses a Java specific string encoding and I doubt that this is what the device really expects.

Except for that, if the device is really implementing the telnet protocol properly (and not just something which can be accessed with a telnet client), you have to either use a Java telnet library to support control sequences or implement this yourself. You can't just read and write to the socket as in your example code.

Upvotes: 1

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81684

I don't know what sort of device you're talking to, but if you normally type commands to it using telnet, you're presumably sending newlines to it, and perhaps those newlines are needed as command terminators. So perhaps

dataOutputStream.writeUTF("}Rv!\n");

or

dataOutputStream.writeUTF("}Rv!\r\n");

(along with uncommenting that call to flush()) would work better.

Upvotes: 3

Related Questions