发送端:
- package com.kxg_04;
- import java.io.IOException;
- import java.net.DatagramPacket;
- import java.net.DatagramSocket;
- import java.net.InetAddress;
- import java.util.Scanner;
- public class SendDemo {
- public static void main(String[] args) throws IOException {
- DatagramSocket ds = new DatagramSocket();
- Scanner sc = new Scanner(System.in);
- String s = null;
- while ((s = sc.nextLine()) != null) {
- byte[] bys = s.getBytes();
- DatagramPacket dp = new DatagramPacket(bys, bys.length,
- InetAddress.getByName("10.164.22.254"), 48264);
- // 发送数据
- ds.send(dp);
- if (s.equals("我下了")) {
- break;
- }
- }
- // 释放资源
- ds.close();
- }
- }
复制代码
接收端:
- package com.kxg_03;
- import java.io.IOException;
- import java.net.DatagramPacket;
- import java.net.DatagramSocket;
- public class ReceiveDemo {
- public static void main(String[] args) throws IOException {
- DatagramSocket ds = new DatagramSocket(48264);
- // 需要多次接受发来的数据,用while循环,而且需要一直保持开启的状态
- while (true) {
- byte[] bys = new byte[1024];
- DatagramPacket dp = new DatagramPacket(bys, bys.length);
- ds.receive(dp);
- String ip = dp.getAddress().getHostAddress();
- String s = new String(dp.getData(), 0, dp.getLength());
- System.out.println(ip + ":" + s);
- }
- }
- }
复制代码
|
|