UDP socket

接收端java

//監聽指定端口 PORT端口號
DatagramSocket dSocket = new DatagramSocket(PORT);
DatagramPacket dPacket = new DatagramPacket(msg, msg.length);
while (life) {
    try {
        //監聽服務器發送來的信息
        dSocket.receive(dPacket);
//      Log.i("msg sever received", new String(dPacket.getData()).trim());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

發送端服務器

//SERVER_ADDRESS 接收端地址 wwww.baidu.com 或 198.168.1.1 SERVER_PORT 服務端端口
try {
    DatagramSocket dSocket = new DatagramSocket();
    InetAddress serviceAddress = InetAddress.getByName(SERVER_ADDRESS);
    DatagramPacket dPacket = new DatagramPacket(msg.getBytes(), msg.length(), serviceAddress, SERVER_PORT);
    //發送信息
    dSocket.send(dPacket);
} catch (IOException e) {
    e.printStackTrace();
}
相關文章
相關標籤/搜索