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();
}
相关文章
相关标签/搜索