黄沙百战穿金甲,不破楼兰终不还。这篇文章主要讲述android thread / udp socket sample相关的知识,希望能为你提供帮助。
class EventReadThread extends Thread {
boolean socketCreated = false;
DatagramSocket socket;
InetAddress serverAddress;
byte dataIn[] = new byte[1024];
private void Delay(int ms) {
try {
Thread:
sleep(ms);
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
while (mThreadQuitFlag == 0) {
Delay(2000);
【android thread / udp socket sample】
if (socketCreated == false) {
try {
socket = new DatagramSocket(4599);
serverAddress = InetAddress.getByName("192.168.0.23");
//127.0.0.1");
String str = "gmx ls";
byte data[] = str.getBytes();
DatagramPacket packet = new DatagramPacket(data, data.length, serverAddress, 4568);
socket.send(packet);
socketCreated = true;
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Read data from udp socket");
try {
DatagramPacket packetIn = new DatagramPacket(dataIn, dataIn.length,serverAddress, 4568);
socket.receive(packetIn);
String result = new String(packetIn.getData(), packetIn.getOffset(), packetIn.getLength());
System.out.println("gmx client result--->
" + result);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("gmx client quit");
return;
}
}
}
class ServerThread extends Thread {
private void Delay(int ms) {
try {
Thread:
sleep(ms);
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
try {
DatagramSocket socket = new DatagramSocket(4567);
byte data[] = new byte[1024];
DatagramPacket packet = new DatagramPacket(data, data.length);
socket.receive(packet);
String result = new String(packet.getData(), packet.getOffset(), packet.getLength());
System.out.println("gmx server result--->
" + result);
String str = "gmx server echo";
byte dataOut[] = str.getBytes();
DatagramPacket packetOut = new DatagramPacket(dataOut, dataOut.length, packet.getAddress(),packet.getPort());
socket.send(packetOut);
System.out.println("gmx server quit");
} catch (Exception e) {
e.printStackTrace();
}
}
}
...
new ServerThread().start();
new EventReadThread().start();
推荐阅读
- Appium环境的安装以及一路上的坑
- Android开源库美团等APP城市选择
- android studio 清空缓存插件
- mybatis通用mapper源码解析
- DeepLearning.ai-Week4-Face Recognition for the Happy House
- Android系统的智能指针(轻量级指针强指针和弱指针)的实现原理分析
- Spring Boot 整合 Apache Solr 异常:Expected mime type application/octet-stream but got text/html 的解决.
- 实例化Flask的参数 及 对app的配置
- tomcat 虚拟目录配置appBase和docBase的区别