- /**
- * @author 不安份的程序猿
- *
- */
- //UDP协议实现 输出数据
- public class DemoGet {
- public static void main(String[] args) throws Exception {
- final DatagramSocket get = new DatagramSocket(9999); // 创建接口
- final boolean t = true;
- new Thread(new Runnable() {
- @Override
- public void run() {
- while (t) {
- // 接收set发送的消息
- byte[] b = new byte[1024]; //
- DatagramPacket dp = new DatagramPacket(b, b.length);// 将从b到b.length都进行打包
- try {
- get.receive(dp);
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } // 接受这个包
- int length = dp.getLength();// 获取这个包的长度
- // System.out.println(new String(b,0,length)); //转化成字符串然后输出
- System.out.println("消息是由" + dp.getAddress() + "发送的,端口是:"
- + dp.getPort() + "内容是" + new String(b, 0, length));
- }
- }
- }).start();
- new Thread(new Runnable() {
- @Override
- public void run() {
- while (t) {
- // 往set回复消息
- try {
- Scanner sc = new Scanner(System.in);
- String str = sc.nextLine();
- DatagramPacket send = new DatagramPacket(
- str.getBytes(), str.getBytes().length,
- InetAddress.getLocalHost(), 6666);
- get.send(send);
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }).start();
- // get.close();
- }
- }
复制代码 |
|