Android为TV端助力 UDP协议
废话不多说。直接上代码!
一. 接收端
1.创建UDP连接
public void init() {
try {
//开关的作用
isRunning = true;
DatagramSocket mUdpSocket = new DatagramSocket(40000);
recivRequest();
} catch (Exception e) {
LogUtil.e(Constant.LOG_TAG, "Exception=" + e);
}
}
2.获取UDP协议的数据包
public void recivRequest() {
//这是一个线程池,用于处理耗时操作
ThreadPoolManager.getInstance().addTask(new Runnable() {
@Override
public void run() {
while (isRunning) {
try {
byte[] recvBuffer = new byte[1024];
DatagramPacket dataPacket = new DatagramPacket(recvBuffer, recvBuffer.length);
mUdpSocket.receive(dataPacket);
parsePackage(dataPacket);
} catch (IOException e) {
if (null != mUdpSocket && !mUdpSocket.isClosed()) {
mUdpSocket.close();
}
mUdpSocket = null;
e.printStackTrace();
}
}
}
});
}
3.开始准备解析UDP协议的数据包
private void parsePackage(final DatagramPacket dataPacket) {
ThreadPoolManager.getInstance().addTask(new Runnable() {
@Override
public void run() {
String [] datagramPacketSegment = getDatagramPacketSegment(dataPacket);
/*得到数据根据自己的业务需求来做*/
}
});
}
4.解析数据包的方法
private String[] getDatagramPacketSegment(DatagramPacket dataPacket) {
if (null == dataPacket) {
return null;
}
int length = 0;
byte[] bytes = dataPacket.getData();
for (int i = 0; i < bytes.length; i++) {
if (bytes[i] == 0) {
length = i;
break;
}
length = i + 1;
}
String recivContent = new String(bytes, 0, length);
//这个#是跟发送端商量好的间隔符,用于区分多条消息
String[] reciveString = recivContent.split("#");
return reciveString;
}
二.发送端
这个方法接收两个参数,一个是客户端IP,一个是你要发送的内容,如果有多条内容用#号区别
public void sendInteractiveRequest(String ipAddress, String contents) {
LogUtil.d(Constant.LOG_TAG, "sendInteractiveRequest--->sendContents=" + contents);
byte[] data = contents.getBytes();
byte[] recvBuffer = new byte[1024];
DatagramPacket dataPacket = new DatagramPacket(recvBuffer, recvBuffer.length);
dataPacket.setData(data);
dataPacket.setLength(data.length);
// 设置此数据包包的目标主机的端口号
dataPacket.setPort(40000);
InetAddress sendAddr = null;
try {
//根据给定的主机字符串名称返回主机的地址
sendAddr = InetAddress.getByName(ipAddress);
//设置接收端主机的地址
dataPacket.setAddress(sendAddr);
//发送数据
mUdpSocket.send(dataPacket);
} catch (Exception e) {
LogUtil.e(Constant.LOG_TAG, "Exception=" + e);
}
}
比如我是这样发的:参数是你要发送的遥控器的key值
private void sendKeycodeValue(final int keyCode) {
CommonUtil.setControllerVibrate(LVBXApp.getApp());
String pairedName = UserMgr.getUserName();
// 发送按键模拟操作指令
ThreadPoolManager.getInstance().addTask(new Runnable() {
@Override
public void run() {
String mainCmd = RemoteCMDType.PAD_CMD + "";
// 101#15754#99065918#10#78:F7:BE:52:61:2A(cmdType#accountName#interactivePasswd#macAddress#keyCodeValue)
String contents = mainCmd + "#" + UserMgr.getUserName() + "#" + UserMgr.getInteracPassword() + "#"
+ CommonUtil.getLocalMacAddress(LVBXApp.getApp()) + "#" + keyCode;
String ipAdress = UserMgr.getPairedIp();
InteractiveMgr.getInstance().sendInteractiveRequest(ipAdress, contents);
}
});
}
OK.UDP通讯解析到此为止,你可以结合我的上一篇文件(模拟发送遥控器指令),远程用手机端发送指令控制电视端!