码迷,mamicode.com
首页 > 编程语言 > 详细

Java之UDP协议 发送与接收简单实现代码

时间:2016-03-20 19:31:51      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:

SendDemo:

package com.renhongwei.demo_01;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
/*
 * UDP数据发送端
 */
public class SendDemo {
    public static void main(String[] args) throws IOException {
        // 创建socket对象
        DatagramSocket ds = new DatagramSocket();
        // 创建打包数据
        byte[] bys = "Hello,world".getBytes();
        int length = bys.length;
        String host = "renhongwei-pc";
        InetAddress address = InetAddress.getByName(host);
        int port = 10086;
        DatagramPacket dp = new DatagramPacket(bys,length,address,port);
        // 发送数据
        ds.send(dp);
        // 释放资源
        ds.close();
    }
}

ReceiveDemo:

package com.renhongwei.demo_01;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
/*
 * UDP接收数据端
 */
public class ReceiveDemo {
    public static void main(String[] args) throws IOException {
        // 设置端口
        int port = 10086;
        // 创建socket对象
        DatagramSocket ds = new DatagramSocket(port);
        // 创建数据包(接收容器)
        byte[] bys = new byte[1024];
        int length = bys.length;
        DatagramPacket dp = new DatagramPacket(bys,length);
        // 调用socket方法接收数据
        ds.receive(dp);
        // 获取IP地址
        InetAddress address = dp.getAddress();
        String ip = address.getHostAddress();
        // 解析数据包
        byte[] bys2 = dp.getData();
        int length2 = dp.getLength();
        String str = new String(bys,0,length2);
        System.out.println(ip + "----" + str);
        // 释放资源
        ds.close();
    }
}

 

Java之UDP协议 发送与接收简单实现代码

标签:

原文地址:http://www.cnblogs.com/renhongwei/p/5299131.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!