个人也同意网上的一些观点,Android开发中尽量不使用UDP进行数据通信。
个人观点:1,UDP不能保证数据传输。2,有的手机不能接收UDP数据包。3,个人觉得用HTTP协议更方便,也更能保证数据传输。
不过有的项目,肯定还是要用到UDP协议,在目前项目中用到了UDP,就简单做个总结。代码还需要优化。
UDP工具类:
public class UdpMessageTool {
private byte[] bytes = new byte[2048];
private DatagramSocket mDatagramSocket = null;
public static UdpMessageTool instance;
public UdpMessageTool() throws Exception {
mDatagramSocket = new DatagramSocket();
}
public static UdpMessageTool getInstance() throws Exception {
if (instance == null) {
instance = new UdpMessageTool();
}
return instance;
}
public final void setTimeOut(final int timeout) throws Exception {
mDatagramSocket.setSoTimeout(timeout);
}
public final DatagramSocket getDatagramSocket() {
return mDatagramSocket;
}
public final synchronized void send(final String host, final int port,
final byte[] bytes) throws IOException {
DatagramPacket dp = new DatagramPacket(bytes, bytes.length,
InetAddress.getByName(host), port);
mDatagramSocket.send(dp);
}
public final synchronized String receive(final String hostName,
final int hostPort) {
DatagramPacket dp = new DatagramPacket(bytes, bytes.length);
try {
mDatagramSocket.receive(dp);
} catch (Exception e) {
e.printStackTrace();
return "";
}
String result = new String(dp.getData(), 0, dp.getLength());
return result;
}
public final void close() {
if (mDatagramSocket != null) {
try {
mDatagramSocket.close();
} catch (Exception ex) {
ex.printStackTrace();
}
mDatagramSocket = null;
}
}
}
在Activity中操作
public class MainActivity extends Activity {
private UdpMessageTool mUdpMessageTool;
private static final String HOST = "192.168.0.0";
private static final int PORT = 12345;
private static final String CONTENT = "SEND MESSAGE?key1=abc&key2=cba";
private Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
String result = (String) msg.obj;
if (!TextUtils.isEmpty(result)) {
Toast.makeText(MainActivity.this, "收到的数据是:" + result,
Toast.LENGTH_SHORT).show();
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.udp).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
new Thread(new Runnable() {
@Override
public void run() {
sendDataByUDP();
}
}).start();
}
});
}
private void sendDataByUDP() {
try {
mUdpMessageTool = UdpMessageTool.getInstance();
mUdpMessageTool.setTimeOut(5000);
mUdpMessageTool.send(HOST, PORT, CONTENT.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
try {
String result = mUdpMessageTool.receive(HOST, PORT);
Thread.sleep(2000);
if (result == null) {
Message msg = new Message();
msg.obj = result;
mHandler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
}
mUdpMessageTool.close();
}
}