Search code examples
javaweb-applicationsjakarta-eetelnet

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?


Solution

  • 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.