[英]how to write bytes to server socket
I'm writing a java socket program to read data from server, I've no control to server, below is protocol agreed, 我正在编写一个Java套接字程序来从服务器读取数据,我无法控制服务器,以下是协议的约定,
For Example: if my request is "command/1/getuserlist" how to construct th request match above protocol and read the response back to List 例如:如果我的请求是“ command / 1 / getuserlist”,则如何构造以上协议的请求匹配并将响应读回到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();
}
}
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. 请注意,如果您声明直接接受
short
幻数的方法,则由于Java中对short
进行了签名,因此您将无法传递文字幻数> 32767
。
Use a DataOutputStream
around a BufferedOutputStream
around the `Socket.getOutputStream(). 在Socket.getOutputStream()的
BufferedOutputStream
周围使用DataOutputStream
。 Then you can use: 然后,您可以使用:
writeShort()
for the magic number writeShort()
writeShort()
for the length word writeShort()
write()
for the payload. write()
。 Similarly you can use DataInputStream
and the corresponding readXXX()
methods to read the response. 同样,您可以使用
DataInputStream
和相应的readXXX()
方法来读取响应。
NB You are writing to a socket here, not a server socket. 注意:您正在此处写入套接字,而不是服务器套接字。
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. DataxxxStream-尽管非常方便-不能完全支持大小端数字和任意String编码。
See my post at How to Read Byte Stream from Socket 请参阅我的文章如何从套接字读取字节流
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.