Android开发之局域网UDP传输

来源:互联网 发布:串口收到的数据都是0 编辑:程序博客网 时间:2024/06/16 00:41

/* * udp发送类 */public class UdpSend {public void send(String command, InetAddress ip) throws IOException {DatagramPacket dp = new DatagramPacket(command.getBytes(),command.getBytes().length, ip, 8898);System.out.println(ip);DatagramSocket ds = new DatagramSocket();ds.send(dp);ds.close();System.out.println("发送成功:"+command);}}

/* * udp接收类 */import java.io.IOException;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;public class UdpReceive {public InetAddress ip = null;public String data;public void Receive() throws IOException {System.out.println("-->进入接收端");DatagramSocket ds = new DatagramSocket(8899);byte[] buf = new byte[1024];DatagramPacket dp = new DatagramPacket(buf, buf.length);ds.receive(dp);ip = dp.getAddress();data = new String(dp.getData(), 0, dp.getLength());ds.close();System.out.println("-->ip:"+ip+"\n-->数据:"+data); System.out.println("-->接收成功");}}




选用8898端口进行通信

UdpSend类中方法参数为发送的命令和目的ip地址。

需要使用时只需new一个新对象,调用方法即可。

0 0
原创粉丝点击