我通过socket连接传输,将字符串大小转成网络字节,然后将传输的字符串转成byte数组,那怎么把网络字节和byte数组相加传输呢,直接相加会出错的,请问这样传输对吗?请给出具体方法,有这方面经验的请帮帮忙啊,谢谢!
例:
public void getStr(){
String strSendXml = "<name id="name" value="aaaaaaa">";
byte[] size=toLH(strSendXml.length());
server=new Socket("197.0.0.17",8888);
PrintWriter out = new PrintWriter(server.getOutputStream());
out.println(size+strSendXml.getBytes());
out.flush();
}
//转成网络字节
public static byte[] toLH(int n) {
byte[] b = new byte[4];
b[0] = (byte) (n & 0xff);
b[1] = (byte) (n >> 8 & 0xff);
b[2] = (byte) (n >> 16 & 0xff);
b[3] = (byte) (n >> 24 & 0xff);
return b;
}
例:
public void getStr(){
String strSendXml = "<name id="name" value="aaaaaaa">";
byte[] size=toLH(strSendXml.length());
server=new Socket("197.0.0.17",8888);
PrintWriter out = new PrintWriter(server.getOutputStream());
out.println(size+strSendXml.getBytes());
out.flush();
}
//转成网络字节
public static byte[] toLH(int n) {
byte[] b = new byte[4];
b[0] = (byte) (n & 0xff);
b[1] = (byte) (n >> 8 & 0xff);
b[2] = (byte) (n >> 16 & 0xff);
b[3] = (byte) (n >> 24 & 0xff);
return b;
}
byte[] message = "需要传输的字符串".getByte();
int length = message.length;
ByteBuffer buf = ByteBuffer.allocate(length + 4);
buf.setAutoExpand(true); byte[] lens = new byte[4];
lens[0] = (byte) ((0xFF000000 & length) >> 24);
lens[1] = (byte) ((0x00FF0000 & length) >> 16);
lens[2] = (byte) ((0x0000FF00 & length) >> 8);
lens[3] = (byte) (0x000000FF & length); buf.put(lens);
buf.put(); buf.flip();
[/code]
String str = ".....";
out.println(str);
可以分两次写:先写size, 再写strSendXml
PrintWriter out = new PrintWriter(server.getOutputStream());
out.println(size);
out.println(strSendXml.getBytes());2>.你为什么要转成网络字节,是要和其他语言比如C++通讯吗? 如果只是JAVA进程的通讯,不需要转成网络字节的, JAVA的SOCKET通讯会内部做掉,不象C++,需要自己转.
3>.如果要和C/C++通讯,转的时候用PrintStream,PrintWriter会加入很多标识符,
你可以直接把strSendXml.length()发送出去.
//byte[] bs2;
ByteBuffer fullBuffer = ByteBuffer.allocate(bs1.length() + bs2.length);
fullBuffer.put(bs1);
fullBuffer.put(bs2);
fullBuffer.flip();
byte[] targetbs = fullBuffer.array();