how to write bytes to server socket

前端 未结 3 1458
故里飘歌
故里飘歌 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.

提交回复
热议问题