Socket send and receive byte array

后端 未结 4 1768
名媛妹妹
名媛妹妹 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:24

    First, do not use DataOutputStream unless it’s really necessary. Second:

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

    Of course this lacks any error checking but this should get you going. The JDK API Javadoc is your friend and can help you a lot.

    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
  • 2020-12-05 05:27

    You need to either have the message be a fixed size, or you need to send the size or you need to use some separator characters.

    This is the easiest case for a known size (100 bytes):

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

    In this case DataInputStream makes sense as it offers readFully(). If you don't use it, you need to loop yourself until the expected number of bytes is read.

    0 讨论(0)
  • 2020-12-05 05:42

    There is a JDK socket tutorial here, which covers both the server and client end. That looks exactly like what you want.

    (from that tutorial) This sets up to read from an echo server:

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

    taking a stream of bytes and converts to strings via the reader and using a default encoding (not advisable, normally).

    Error handling and closing sockets/streams omitted from the above, but check the tutorial.

    0 讨论(0)
提交回复
热议问题