如何在Java中将数组写入outputStream [英] how to write array to outputStream in Java

查看:1001
本文介绍了如何在Java中将数组写入outputStream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过Socket发送多个随机值。我认为数组是发送它们的最佳方式。但我不知道如何将数组写入Socket outputStream?

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 ?

我的java类

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

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




 }


推荐答案

使用java.io.DataOutputStream / DataInputStream对,他们知道如何读取整数。将信息作为长度+随机数的数据包发送。

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

发件人

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

接收器

 DataInputStream in = new DataInputStream(sock.getInputStream());
 int len = in.readInt();
 for(int i = 0; i < len; i++) {
      int next = in.readInt();
 ...

这篇关于如何在Java中将数组写入outputStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆