说明
测试程序分为两个部分:Android客户端、Java服务端。
- Android客户端:向局域网UDP广播字符串“Hello, World!”,端口号是11000。然后打印所有收到的UDP广播。
- Java服务端:监听11000的UDP广播,收到UDP广播后,发送一个JSON串。
Android客户端
public class MainActivity extends Activity {
// UDP广播IP和PORT
public static final String SERVERIP = "255.255.255.255";
public static final int SERVERPORT = 11000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Client()).start();
}
DatagramSocket socket = null;
public class Client implements Runnable {
public void run() {
// 向局域网UDP广播信息:Hello, World!
try {
InetAddress serverAddress = InetAddress.getByName(SERVERIP);
System.out.println("Client: Start connecting\n");
socket = new DatagramSocket(SERVERPORT);
byte[] buf = "Hello, World!".getBytes();
DatagramPacket packet = new DatagramPacket(buf, buf.length,
serverAddress, SERVERPORT);
System.out.println("Client: Sending ‘" + new String(buf)
+ "’\n");
socket.send(packet);
System.out.println("Client: Message sent\n");
System.out.println("Client: Succeed!\n");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 接收UDP广播,有的手机不支持
while (true) {
byte[] recbuf = new byte[255];
DatagramPacket recpacket = new DatagramPacket(recbuf,
recbuf.length);
try {
socket.receive(recpacket);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Server: Message received: ‘"
+ new String(recpacket.getData()) + "’\n");
System.out.println("Server: IP " + recpacket.getAddress()
+ "’\n");
}
}
}
}
AndroidManifest中添加Internet权限
<uses-permission android:name="android.permission.INTERNET" />
Java服务端
class UDPServer {
public static void main(String[] args) throws IOException {
DatagramSocket server = new DatagramSocket(11000);
while (true) {
byte[] recvBuf = new byte[100];
DatagramPacket recvPacket = new DatagramPacket(recvBuf,
recvBuf.length);
server.receive(recvPacket);
String recvStr = new String(recvPacket.getData(), 0,
recvPacket.getLength());
System.out.println();
System.out.println("收到的内容:" + recvStr);
System.out.println("收到的ip:" + recvPacket.getAddress());
// 发送UDP消息,JSON格式数据
// {"name":"123","ID":"Robot007","BATTERY":"2.7f"}
int port = recvPacket.getPort();
InetAddress addr = recvPacket.getAddress();
JSONObject json = new JSONObject();
json.put("name", "Computer7");
json.put("ID", "Robot007");
json.put("BATTERY", "2.7f");
byte[] sendBuf = json.toString().getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendBuf,
sendBuf.length, addr, port);
server.send(sendPacket);
}
}
}