Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write array to OutputStream in Java?

I want to send more than one random value though Socket. I think array is the best way to send them. But I don't know how to write an array to Socket OutputStream?

My Java class:

import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import java.io.*; import java.util.Random;

public class NodeCommunicator {

    public static void main(String[] args) {
        try {
            Socket nodejs = new Socket("localhost", 8181);

            Random randomGenerator = new Random();
            for (int idx = 1; idx <= 1000; ++idx){
                Thread.sleep(500);
                int randomInt = randomGenerator.nextInt(35);
                sendMessage(nodejs, randomInt + " ");
                System.out.println(randomInt);
            }

            while(true){
                Thread.sleep(1000);
            }
        } catch (Exception e) {
            System.out.println("Connection terminated..Closing Java Client");
            System.out.println("Error :- "+e);
        }
    }

    public static void sendMessage(Socket s, String message) throws IOException {
        s.getOutputStream().write(message.getBytes("UTF-8"));
        s.getOutputStream().flush();
    }

}
like image 667
Abhijit Muke Avatar asked Dec 21 '12 04:12

Abhijit Muke


People also ask

Can you write an array to an ObjectOutputStream?

You can use ObjectOutputStream to write array to outputstream at one swoop.

How do you write OutputStream in java?

Methods of OutputStreamwrite() - writes the specified byte to the output stream. write(byte[] array) - writes the bytes from the specified array to the output stream. flush() - forces to write all data present in output stream to the destination. close() - closes the output stream.

How do you declare OutputStream?

void write(byte[] b) : Writes b. length bytes from the specified byte array to this output stream. void write(byte[] b, int off, int len) : Writes len bytes from the specified byte array starting at offset off to this output stream. abstract void write(int b) : Writes the specified byte to this output stream.


2 Answers

Use java.io.DataOutputStream / DataInputStream pair, they know how to read ints. Send info as a packet of length + random numbers.

sender

Socket sock = new Socket("localhost", 8181);
DataOutputStream out = new DataOutputStream(sock.getOutputStream());
out.writeInt(len);
for(int i = 0; i < len; i++) {
      out.writeInt(randomGenerator.nextInt(35))
...

receiver

 DataInputStream in = new DataInputStream(sock.getInputStream());
 int len = in.readInt();
 for(int i = 0; i < len; i++) {
      int next = in.readInt();
 ...
like image 68
Evgeniy Dorofeev Avatar answered Sep 28 '22 09:09

Evgeniy Dorofeev


Java arrays are actually Objects and moreover they implement the Serializable interface. So, you can serialize your array, get the bytes and send those through the socket. This should do it:

public static void sendMessage(Socket s, int[] myMessageArray)
   throws IOException {
  ByteArrayOutputStream bs = new ByteArrayOutputStream();
  ObjectOutputStream os = new ObjectOutputStream(bs);
  os.writeObject(myMessageArray);
  byte[] messageArrayBytes = bs.toByteArray();
  s.getOutputStream().write(messageArrayBytes);
  s.getOutputStream().flush();
}

What's really neat about this is that it works not only for int[] but for any Serializable object.

Edit: Thinking about it again, this is even simpler:

sender:

public static void sendMessage(Socket s, int[] myMessageArray)
   throws IOException {
  OutputStream os = s.getOutputStream();  
  ObjectOutputStream oos = new ObjectOutputStream(os);  
  oos.writeObject(myMessageArray); 
}

receiver:

public static int[] getMessage(Socket s)
   throws IOException {
  InputStream is = s.getInputStream();  
  ObjectInputStream ois = new ObjectInputStream(is);  
  int[] myMessageArray = (int[])ois.readObject(); 
  return myMessageArray;
}

I'm leaving my first answer also as(it also works and) it's useful for writing objects to UDP DatagramSockets and DatagramPackets where there is no stream.

like image 25
AFS Avatar answered Sep 28 '22 07:09

AFS