Java: how to send and receive data using a socket?

advertisements

I'm building a middleware, where I need to constantly read what is happening in my device, so I build 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 {
            // ip and port where is my device
            Socket socket = new Socket("192.168.1.4", 2001);

            DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());

            DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());

            // i need send this parameter to my device
            dataOutputStream.writeUTF("}Rv!");

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

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

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

Output:

IOEXCEPTION Connection reset

What's wrong with my class?


I don't know if this is what is causing your problem, but you are not flushing the output stream before attempting to read a response from the input stream. Try:

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