如何在Java中将数组写入outputStream

前端之家收集整理的这篇文章主要介绍了如何在Java中将数组写入outputStream前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想通过Socket发送多个随机值.我认为数组是发送它们的最佳方式.但是我不知道如何将数组写入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对,他们知道如何读取整数.将信息作为长度随机数的数据包发送.

寄件人

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();
 ...
原文链接:https://www.f2er.com/java/127919.html

猜你在找的Java相关文章