Socket send and receive byte array

后端 未结 4 1783
名媛妹妹
名媛妹妹 2020-12-05 04:44

In server, I have send a byte array to client through Java socket

byte[] message = ... ;

DataOutputStream dout = new DataOutputStream(client.getOutputStream         


        
4条回答
  •  难免孤独
    2020-12-05 05:26

    Try this, it's working for me.

    Sender:

    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
    


    Receiver:

    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
    }
    

提交回复
热议问题