如何将字节写入服务器套接字 [英] how to write bytes to server socket

查看:137
本文介绍了如何将字节写入服务器套接字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个java套接字程序来从服务器读取数据,我无法控制服务器,下面是协议约定,

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


  • 2字节:幻数

  • 2字节:数据长度

  • N字节:ASCII字符串数据有效负载

  • 幻数和数据长度的大端

  • 2-bytes: magic number
  • 2-bytes: data length
  • N-bytes: ASCII string data payload
  • Big endian for the magic number and data length

例如:如果我的请求是command / 1 / getuserlist 如何构造请求匹配上面的协议并将响应读回List

For Example: if my request is "command/1/getuserlist" how to construct th request match above protocol and read the response back to List

我是套接字编程的新手,并且不知道如何构建我的请求并阅读回复。

I'm new to socket programming and have no idea how to build my request and read the response back.

有人可以指导我如何构建请求并阅读来自

can someone guide me how to build the request and read the response from

推荐答案

根据规范,你必须建立一个以下列方式塑造的数据包

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();
    }
}

请注意,如果您声明方法接受<直接code>短幻数,你将无法传递一个字面幻数> 32767 因为 short 是用Java签名的。

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.

这篇关于如何将字节写入服务器套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆