TCP Socket 通信
在物联网开发中,通过串口服务器将串口数据转化成网络信号,服务器与终端之间的链接就相应的变成了TCP client 与TCP server链接了,中间传输的数据仍为HEX(十六进制)的指令。
在此 TCP 两部分的实现代码如下(仅做参考):
1. TCP client
关键代码
/**
* 发送并接受TCP请求
*
* @param IP 远程主机地址
* @param port 远程主机端口
* @param reqData 待发送报文的中文字符串形式
* @return localPort--本地绑定的端口,reqData--请求报文,respData--响应报文,respDataHex--远程主机响应的原始字节的十六进制表示
*/
private static byte[] sendTCPRequest(String IP, String port, String reqData) {
byte[] resbyte = null;
OutputStream out = null; //写
InputStream in = null; //读
Socket socket = new Socket(); //客户机
try {
socket.setTcpNoDelay(true);
socket.setReuseAddress(true);
socket.setSoTimeout(10000);
socket.setSoLinger(true, 5);
socket.setSendBufferSize(1024);
socket.setReceiveBufferSize(1024);
socket.setKeepAlive(true);
socket.connect(new InetSocketAddress(IP, Integer.parseInt(port)), 10000);
/**
* 发送HTTP请求
*/
out = socket.getOutputStream();
out.write(ByteUtil.hexStringToBytes(reqData));
/**
* 接收HTTP响应
*/
in = socket.getInputStream();
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
byte[] buffer = new byte[256];
int len = -1;
while ((len = in.read(buffer)) != -1) {
bytesOut.write(buffer, 0, len);
break;
}
/**
* 解码HTTP响应的完整报文
*/
resbyte = bytesOut.toByteArray();
} catch (Exception e) {
System.out.println("与[" + IP + ":" + port + "]通信遇到异常,堆栈信息如下");
e.printStackTrace();
} finally {
if (null != socket && socket.isConnected() && !socket.isClosed()) {
try {
socket.close();
} catch (IOException e) {
System.out.println("关闭客户机Socket时发生异常,堆栈信息如下");
e.printStackTrace();
}
}
}
return resbyte;
}
全代码
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.utils.ByteUtil;
import com.utils.TimeUtil;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
/**
* 使用JavaSocket编写发送TCP请求的工具类
*
* @author 玄玉<http://blog.csdn.net/jadyer>
* @create Apr 5, 2013 9:25:34 PM
*/
public class TCPUtil {
private TCPUtil() {
}
/**
* 发送并接受TCP请求
*
* @param IP 远程主机地址
* @param port远程主机端口
* @param reqData 待发送报文的中文字符串形式
* @return localPort--本地绑定的端口,reqData--请求报文,respData--响应报文,respDataHex--远程主机响应的原始字节的十六进制表示
*/
private static byte[] sendTCPRequest(String IP, String port, String reqData) {
byte[] resbyte = null;
OutputStream out = null; //写
InputStream in = null;//读
Socket socket = new Socket(); //客户机
try {
socket.setTcpNoDelay(true);
socket.setReuseAddress(true);
socket.setSoTimeout(10000);
socket.setSoLinger(true, 5);
socket.setSendBufferSize(1024);
socket.setReceiveBufferSize(1024);
socket.setKeepAlive(true);
socket.connect(new InetSocketAddress(IP, Integer.parseInt(port)), 10000);
/**
* 发送HTTP请求
*/
out = socket.getOutputStream();
out.write(ByteUtil.hexStringToBytes(reqData));
/**
* 接收HTTP响应
*/
in = socket.getInputStream();
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
byte[] buffer = new byte[256];
int len = -1;
while ((len = in.read(buffer)) != -1) {
bytesOut.write(buffer, 0, len);
break;
}
/**
* 解码HTTP响应的完整报文
*/
resbyte = bytesOut.toByteArray();
} catch (Exception e) {
System.out.println("与[" + IP + ":" + port + "]通信遇到异常,堆栈信息如下");
e.printStackTrace();
} finally {
if (null != socket && socket.isConnected() && !socket.isClosed()) {
try {
socket.close();
} catch (IOException e) {
System.out.println("关闭客户机Socket时发生异常,堆栈信息如下");
e.printStackTrace();
}
}
}
return resbyte;
}
/**
* 发送并获取返回信号
*
* @param IP
* @param port
* @param reqData
* @return
*/
public static Record sendAndGetData(String IP, String port, String reqData) {
byte[] res = TCPUtil.sendTCPRequest(IP, port, reqData);
Record item = new Record();
item.set("ip", IP);
item.set("portstr", port);
item.set("send", reqData);
item.set("accept", ByteUtil.toHexString1(res));
item.set("accepttime", TimeUtil.getNowTime());
//保存发送返回记录
Db.save("t_log", item); //保存请求日志
item.set("acceptData", res);
return item;
}
/**
* @param srcbyte数组
* @param offset 从数组的第offset位开始
* @return int数值
*/
public static int bytesToInt(byte[] src, int offset) {
int value;
value = (int) (((src[offset] & 0xFF)<<8)
| ((src[offset + 1] & 0xFF)));
return value;
}
/**
* byte数组中取int数值,本方法适用于(低位在后,高位在前)的顺序。和intToBytes2()配套使用
*/
public static int bytesToInt2(byte[] src, int offset) {
int value;
value = (int) ( ((src[offset] & 0xFF)<<24)
|((src[offset+1] & 0xFF)<<16)
|((src[offset+2] & 0xFF)<<8)
|(src[offset+3] & 0xFF));
return value;
}
public static void main(String[] args) {
String reqData = "010300000002C40B";
String IP = "192.168.0.199";
String port = "1030";
}
}