项目中用到socket进行数据上传,一般规定消息体发送规则都是 [消息体大小][消息体]
首先定义拼包方法,定制需要版本号 命令码 和发送数据的方式,这里以宇视服务器为例。
/**
* 流量拼包
*
* @param editID 版本协议大小
* @param cmdID 命令码大小
* @param object 存放xml文档信息的byte数组
* @return
*/
public static byte[] merge(int editID, int cmdID, Object object) {
byte[] begin = intToBytes(0x77aa77aa); //包头(存入byte数组中)
byte[] end = intToBytes(0x77ab77ab); //包尾
byte[] editId = intToBytes(editID); //协议版本
byte[] cmdId = intToBytes(cmdID); //命令码
//车辆信息存入byte数组中
byte[] objectXML = buildXml(object).getBytes();
System.out.println(buildXml(object));
byte[] xmlLen = intToBytes(objectXML.length); //xml长度
int packageLenParam = editId.length + cmdId.length + xmlLen.length + objectXML.length;
byte [] imageNum = intToBytes(0);
if(object instanceof TrafficEvent){
packageLenParam = packageLenParam+ imageNum.length;
}
byte[] packageLen = intToBytes(packageLenParam); //包长
byte[] totalLen = new byte[packageLenParam + begin.length + end.length + packageLen.length]; //整条消息包长度
int i = 0;
/*拼包头*/
for (int j = 0; j < 4; j++) {
totalLen[i] = begin[j];
i++;
}
/*拼包长*/
for (int j = 0; j < 4; j++) {
totalLen[i] = packageLen[j];
i++;
}
/*拼版本协议*/
for (int j = 0; j < editId.length; j++) {
totalLen[i] = editId[j];
i++;
}
/*拼命令码*/
for (int j = 0; j < cmdId.length; j++) {
totalLen[i] = cmdId[j];
i++;
}
/*拼XML长度*/
for (int j = 0; j < xmlLen.length; j++) {
totalLen[i] = xmlLen[j];
i++;
}
/*拼XML信息*/
for (int j = 0; j < objectXML.length; j++) {
totalLen[i] = objectXML[j];
i++;
}
if(object instanceof TrafficEvent){
/*拼图片长度*/
for (int j = 0; j < imageNum.length; j++) {
totalLen[i] = imageNum[j];
i++;
}
}
/*拼包尾*/
for (int j = 0; j < 4; j++) {
totalLen[i] = end[j];
i++;
}
return totalLen;
}
TCP数据的发送
Socket socket = new Socket();
socket.setTcpNoDelay(true);
socket.setReuseAddress(true);
socket.setSoTimeout(30000);
socket.setSoLinger(true, 5);
socket.setSendBufferSize(1024);
socket.setReceiveBufferSize(1024);
socket.setKeepAlive(true);
String ip = Global.getConfig("TCP.Server.ip");
Integer port = Integer.parseInt(Global.getConfig("TCP.Server.port"));
socket.connect(new InetSocketAddress(ip, port), 30000);
//发送TCP
OutputStream os = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.write(msg, 0, msg.length);
InputStream is = socket.getInputStream();
DataInputStream dis = new DataInputStream(is);
byte[] rec = new byte[1024 * 10];
dis.read(rec, 0, rec.length);
String receive = new String(rec, "UTF-8");
logger.info("响应报文" + receive);