How to transfer integer or byte array through socket in java

1.3k views Asked by At

yes i did look at the tutorials on sun and they didn`t help in my case, only transferred the first command.

I`ve got a method

public void openConnection() throws IOException{

    serverSocket = new ServerSocket(5346);

    Socket simSocket = serverSocket.accept();

    is = simSocket.getInputStream();
    os = simSocket.getOutputStream();

    writer = new PrintWriter(os);
    isReader = new InputStreamReader(is);
    reader = new BufferedReader(isReader);

    System.out.println("Connection succesfull.");
}

and

public void sendTo(int command) {
    try {
        writer.println(command);
        writer.flush();
    } catch(Exception e) {
        System.out.println("Error sending command to the robot");
        System.out.println(e.toString());
    }
}

in the sending side, and

public static void setUpConnection() {
    try {
        socket = new Socket(InetAddress.getLocalHost(), 5346);
        is = new InputStreamReader(
                socket.getInputStream());
        reader = new BufferedReader(is);
        writer = new PrintWriter(socket.getOutputStream());
        System.out.println("Simulator: connection succesful");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

and

while (true) {
                intCommand = reader.read();
                ett = reader.readLine(); // does nothing, but without this line it doesn't work
                command = (char) intCommand;

in the receiving side. It works perfectly sending a char or an ascii number of a char. What i need is to change this code to send integers or simply array of bytes instead of a char. if i simply leave just InputStream and OutputStream it does receive the first command and thats it, while these methods continuously receives what is sent through sendTo. Even in sockets documentation they only have exmample with sending chars only.

1

There are 1 answers

2
bdabmxican On BEST ANSWER

Just code your server to store the received value as an int instead of a char.