客户端代码:
/**
* 开启UDP发送
*
* @author gzh
*/
public class Client implements Runnable {
@Override
public void run() {
try {
wifiGPSInfo = new WifiGPSInfo();
wifiGPSInfo.setStatusCode("32");// 签到
Intent intent = getIntent(); // 用于激活它的意图对象
String acc = intent.getStringExtra("acc");
wifiGPSInfo.setAcc(acc);
InetAddress serverAddr = InetAddress.getByName(SERVERIP);
DatagramSocket socket = new DatagramSocket();
byte[] buf;
if (!"".equals(JSON.toJSONString(wifiGPSInfo))) {
buf = (JSON.toJSONString(wifiGPSInfo)).getBytes("gbk");
} else {
buf = ("Default message").getBytes();
}
DatagramPacket packet = new DatagramPacket(buf, buf.length,
serverAddr, SERVERPORT);
socket.send(packet);
socket.close();
} catch (Exception e) {
}
}
}
/**
* 开启UDP接收
*
* @author gzh
*/
class ServerThread extends Thread {
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(), "gb2312");
try {
JSONObject jsonObject = new JSONObject(result);
String code = jsonObject.getString("code");
String msg = jsonObject.getString("msg");
// 签到状态显示
Message message = handler.obtainMessage();// 用此方法避免创建新对象,减少内存的开销
if (code != null && code.equals("1005")) {
message.what = SECUSS;
message.obj = msg;
} else if (code != null && code.equals("1006")) {
message.what = ERROR;
message.obj = msg;
}
handler.sendMessage(message);
} catch (JSONException e) {
e.printStackTrace();
}
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
UDP方式一直存在一个问题,客户端发送请求一次之后,第二次发送请求会一直提示
到现在也没有解决。故暂且不使用UDP方式与服务器交互。
原文地址:http://xhzqbk.blog.51cto.com/9091942/1651459