how to send an array of bytes over a TCP connection (java programming)

前端 未结 9 1743
粉色の甜心
粉色の甜心 2020-12-13 14:45

Can somebody demonstrate how to send an array of bytes over a TCP connection from a sender program to a receiver program in Java.

byte[] myByteArray
<         


        
相关标签:
9条回答
  • 2020-12-13 15:18

    I would ask you to use ObjectOutputStream and ObjectInputStream. These send everything as an object and receive as the same.

    ObjectOutputStream os = new ObjectOutputStream(socket.getOutputStream());
    os.flush();
    ObjectInputStream is = new ObjectInputStream(socket.getInputStream());
    os.writeObject(byte_array_that_you_want_to_send);
    byte[] temp = (byte[]) is.readObject();
    

    Also remember first create the output stream, flush it and then go ahead with the input stream because if something left out in the stream the input stream wont be created.

    0 讨论(0)
  • 2020-12-13 15:24

    This Sun Sockets tutorial should give you a good starting point

    0 讨论(0)
  • 2020-12-13 15:26

    What you need to use is the write method of an java.io.OutputStream, and the read method of an java.io.InputStream, both of which you can retrieve from the Socket you open.

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