AndroidUDP使用Demo
时间: 2023-11-17 11:07:23 浏览: 80
Android UDP demo
4星 · 用户满意度95%
以下是一个使用 Android UDP 的简单示例:
```java
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private static final int PORT = 8888; // 定义端口号
private DatagramSocket socket;
private DatagramPacket packet;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable() {
@Override
public void run() {
try {
// 创建UDP套接字,指定端口号
socket = new DatagramSocket(PORT);
byte[] buf = new byte[1024];
packet = new DatagramPacket(buf, buf.length);
while (true) {
Log.d(TAG, "Waiting for packet...");
// 接收数据包
socket.receive(packet);
String message = new String(packet.getData(), 0, packet.getLength());
Log.d(TAG, "Received message: " + message);
// 发送响应
byte[] response = "Response from server".getBytes();
DatagramPacket responsePacket = new DatagramPacket(response, response.length, packet.getAddress(), packet.getPort());
socket.send(responsePacket);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
socket.close();
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
try {
// 创建UDP套接字
DatagramSocket socket = new DatagramSocket();
InetAddress address = InetAddress.getByName("localhost");
// 发送数据包
String message = "Hello, server!";
byte[] buf = message.getBytes();
DatagramPacket packet = new DatagramPacket(buf, buf.length, address, PORT);
socket.send(packet);
// 接收响应
byte[] responseBuf = new byte[1024];
DatagramPacket responsePacket = new DatagramPacket(responseBuf, responseBuf.length);
socket.receive(responsePacket);
String response = new String(responsePacket.getData(), 0, responsePacket.getLength());
Log.d(TAG, "Received response: " + response);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
```
这个示例中,我们创建了两个线程,一个用于接收数据包和发送响应,另一个用于发送数据包和接收响应。请注意,我们在接收数据包时使用了 `socket.receive(packet)` 方法,该方法会一直阻塞,直到收到数据包。在发送数据包时,我们需要指定目标地址和端口号。最后,在每次发送和接收数据包之后,我们需要关闭套接字。
阅读全文