发送端:
- package com.net;
- import java.net.*;
- public class UdpSend {
- public static void main(String[] args)throws Exception {
- //1、建立socket套接字
- DatagramSocket ds = new DatagramSocket(8080);
-
- //2、
- byte[] buf = "我是数据".getBytes();
- DatagramPacket dp = new DatagramPacket(buf, buf.length,
- InetAddress.getByName("192.168.1.101"),10000);
-
- ds.send(dp);
- ds.close();
- }
- }
复制代码
接收端
- package com.net;
- import java.net.*;
- public class UdpRecv {
- public static void main(String[] args) throws Exception {
-
- DatagramSocket ds = new DatagramSocket(10000);
-
-
- byte[] buf=new byte[1024];
-
- DatagramPacket dp = new DatagramPacket(buf, buf.length);
-
- ds.receive(dp);
-
- String ip = dp.getAddress().getHostAddress();
-
- String data = new String(dp.getData(),0,dp.getLength());
-
- int port = dp.getPort();
-
- System.out.println("ip:"+ip+"\n内容:"+data+"\n端口:"+port);
-
- ds.close();
-
- }
- }
复制代码 |
|