码迷,mamicode.com
首页 > 移动开发 > 详细

android thread / udp socket sample

时间:2018-08-21 13:53:41      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:ace   ams   lse   delay   extends   tst   cat   sam   fse   

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

标签:ace   ams   lse   delay   extends   tst   cat   sam   fse   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!