Java UDP Socket使用2个class: DatagramSocket and DatagramPacket
在DatagramSocket中並不區分ServerSocket和ClientSocket,调用send方法的就相当于socket client,调用receive方法的就相当于socket server。
调用DatagramSocket 的receive方法时,程序就一直停留在receive這個位置,不再往下執行,直到接收到数据(这和ServerSocket是一样的)。因此应该另起一个thread来call receive method。
参考文档:http://big5.webasp.net/article/17/16696.htm
UDP broadcast:该功能只能向在同一个局域网里的devices/PCs来broadcast message。
其原理是:通过DatagramSocket 来send message to局域网的broadcast address “255.255.255.255”。代码是:
private void sendUdpMessage() { String message = "hello world"; try { DatagramSocket socket = new DatagramSocket(4545); socket.setBroadcast(true); InetAddress serverAddr = InetAddress.getByName("255.255.255.255"); DatagramPacket packet = new DatagramPacket(message.getBytes(), message.length(), serverAddr, PORT); socket.send(packet); socket.close(); } catch (Exception e) { Log.e("Error", e.toString()); } }
参考文档:
http://code.google.com/p/boxeeremote/wiki/AndroidUDP
http://code.google.com/p/boxeeremote/wiki/UsingBoxeeRemote
http://kkito.cn/index.php/blog/getArticle/183/java%E5%88%A9%E7%94%A8udp%E5%AE%9E%E7%8E%B0%E5%B9%BF%E6%92%AD
http://blog.xuite.net/ffc99a3b/ooxx/42960121-%5B%E8%BD%89%E8%BC%89%5DAndroid+UDP+Broadcast+Socket
udp broadcast over 3g
http://stackoverflow.com/questions/8525867/android-broadcasting-over-3g
http://stackoverflow.com/questions/7363530/android-3g-udp-broadcast