有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

javasocket发送和接收字节数组

在服务器端,我通过Javasocket向客户端发送字节数组

byte[] message = ... ;

DataOutputStream dout = new DataOutputStream(client.getOutputStream());
dout.write(message);

如何从客户端接收这个字节数组


共 (4) 个答案

  1. # 1 楼答案

    首先,除非确有必要,否则不要使用DataOutputStream。第二:

    Socket socket = new Socket("host", port);
    OutputStream socketOutputStream = socket.getOutputStream();
    socketOutputStream.write(message);
    

    当然,这没有任何错误检查,但这应该让你去。这个JDK API Javadoc是你的朋友,可以帮你很多

  2. # 2 楼答案

    您需要将消息设置为固定大小,或者需要发送大小,或者需要使用一些分隔符

    这是已知大小(100字节)的最简单情况:

    in = new DataInputStream(server.getInputStream());
    byte[] message = new byte[100]; // the well known size
    in.readFully(message);
    

    在这种情况下DataInputStream是有意义的,因为它提供了readFully()。如果不使用它,则需要循环自己,直到读取预期的字节数

  3. # 3 楼答案

    有一个JDK套接字教程here,它涵盖了服务器端和客户端。这和你想要的一模一样

    (来自该教程)设置为从echo服务器读取:

        echoSocket = new Socket("taranis", 7);
        out = new PrintWriter(echoSocket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(
                                    echoSocket.getInputStream()));
    

    获取字节流并通过读卡器转换为字符串,并使用默认编码(通常不建议)

    上面省略了错误处理和关闭套接字/流,但请查看教程

  4. # 4 楼答案

    试试这个,对我有用

    发件人:

    byte[] message = ...
    Socket socket = ...
    DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());
    
    dOut.writeInt(message.length); // write length of the message
    dOut.write(message);           // write the message
    


    接收器:

    Socket socket = ...
    DataInputStream dIn = new DataInputStream(socket.getInputStream());
    
    int length = dIn.readInt();                    // read length of incoming message
    if(length>0) {
        byte[] message = new byte[length];
        dIn.readFully(message, 0, message.length); // read the message
    }