how to write bytes to server socket

前端 未结 3 1459
故里飘歌
故里飘歌 2021-01-27 21:44

I\'m writing a java socket program to read data from server, I\'ve no control to server, below is protocol agreed,

  • 2-bytes: magic number
  • 2-bytes: data l
相关标签:
3条回答
  • 2021-01-27 22:12

    According to the specification you must build a packet shaped in the following way

    | 2 | 2 | N ........ |
    

    Now this could be quite easy and there are multiple ways to do it, I suggest you one:

    import java.nio.ByteBuffer;
    import java.nio.ByteOrder;
    
    static byte[] buildPacket(int magicNumber, String payload) throws UnsupportedEncodingException
    {
      // 4 bytes for header + payload
      ByteBuffer buffer = ByteBuffer.allocate(2 + 2 + payload.length());
      // we set that we want big endian numbers
      buffer.order(ByteOrder.BIG_ENDIAN);
    
      buffer.putShort((short)magicNumber);
      buffer.putShort((short)payload.length());
      buffer.put(payload.getBytes("US-ASCII"));
      return buffer.array();
    }
    
    public static void main (String[] args) throws java.lang.Exception
    {
        try
        {
            byte[] bytes = buildPacket(0xFF10, "foobar");
            for (byte b : bytes)
              System.out.printf("0x%02X ", b);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    

    Mind that if you declare the method to accept a short magic number directly, you won't be able to pass a literal magic number > 32767 because short is signed in Java.

    0 讨论(0)
  • 2021-01-27 22:29

    Watch out for the big endinanness!

    DataxxxStream - although it is quite handy - does not offer a full support for both little and big endian numbers and arbitrary String encodings.

    See my post at How to Read Byte Stream from Socket

    0 讨论(0)
  • 2021-01-27 22:31

    Use a DataOutputStream around a BufferedOutputStream around the `Socket.getOutputStream(). Then you can use:

    • writeShort() for the magic number
    • writeShort() for the length word
    • write() for the payload.

    Similarly you can use DataInputStream and the corresponding readXXX() methods to read the response.

    NB You are writing to a socket here, not a server socket.

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