这是接收端,没有问题
- package com.tg.www;
- import java.net.DatagramPacket;
- import java.net.DatagramSocket;
- public class UdpReceive
- {
- public static void main(String[] args) throws Exception
- {
- //1,创建udp socket,建立端点
- DatagramSocket dSocket = new DatagramSocket(10003);
- //2,定义数据包,用于存放数据
- while (true)
- {
- byte [] buf = new byte[1024];
- DatagramPacket dPacket = new DatagramPacket(buf, buf.length);
- //3,通过数据包的receive()方法攻取其中的数据
- dSocket.receive(dPacket);
- //String ip = dPacket.getAddress().getHostAddress();
- String data = new String(buf, 0, dPacket.getLength());
- //int port = dPacket.getPort();
- System.out.println(data);
- }
-
- //关闭资源
- //dSocket.close();
-
- }
- }
复制代码 这是发送端,为什么不行啊,怎么都看不出问题在哪
- package com.tg.www;
- import java.net.DatagramPacket;
- import java.net.DatagramSocket;
- import java.net.InetAddress;
- import java.util.Scanner;
- public class UdpSend
- {
- public static void main(String[] args) throws Exception
- {
- // 1,通过 DatagramSocket对象创建Udp服务
- // 2,获取键盘输入 ,确定数据
- DatagramSocket dSocket = new DatagramSocket();
- Scanner scanner = new Scanner(System.in);
- while (scanner.hasNextLine())
- {
- String string = scanner.nextLine();
- byte[] buf = string.getBytes();
- // 3,通过DatagramPacket封装成数据包
- DatagramPacket datagramPacket = new DatagramPacket(buf, buf.length,
- InetAddress.getByName("127.0.0.1"), 10003);
- // 4,通过socket服务的send()方法,将已有的数据包发送出去
- dSocket.send(datagramPacket);
- }
-
- // 5,关闭资源
- dSocket.close();
- }
- }
复制代码
|