- package com.itheima.day23;
- import java.io.IOException;
- import java.net.DatagramPacket;
- import java.net.DatagramSocket;
- import java.net.InetAddress;
- import java.net.SocketException;
- import java.net.UnknownHostException;
- public class UdpDemo {
- /**
- * udp发送端
- */
- public static void main(String[] args) {
- try {
- DatagramSocket ds= new DatagramSocket(10000);
- byte [] buf= "ab cd ef j".getBytes();
- DatagramPacket dp=new DatagramPacket(buf, buf.length, InetAddress.getByName("127.0.0.1"),
- 10000);
- ds.send(dp);
- ds.close();
-
-
- } catch (SocketException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (UnknownHostException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
复制代码- package com.itheima.day23;
- import java.io.IOException;
- import java.net.DatagramPacket;
- import java.net.DatagramSocket;
- import java.net.SocketException;
- public class UdpDemo {
- /**
- * 接受发过来的数据
- */
- public static void main(String[] args) {
- try {
- DatagramSocket ds=new DatagramSocket(10000);
- byte [] buf=new byte[1024];
- DatagramPacket dp=new DatagramPacket(buf,buf.length);
- ds.receive(dp);
- ds.close();
- String ip= dp.getAddress().getHostAddress();
- String data = new String(dp.getData(),0,dp.getLength());
- int port = dp.getPort();
- System.out.println(ip+"::"+data+"::"+port);
- } catch (SocketException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- }
- }
复制代码 |