首页 > 移动平台 > 详细

android thread / udp socket sample

时间:2018-08-21 13:48:50      阅读:181      评论:0      收藏:0      [点我收藏+]

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);


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();

android thread / udp socket sample

原文:https://www.cnblogs.com/reboost/p/9510721.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!