Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
655 views
in Technique[技术] by (71.8m points)

sockets - 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();
    }

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();
 ...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...