UDP 消息发送与接收得简单实现

不说UDP是什么了,没意思,直接上demo

测试demo时放在不同得类里面,先启动接收类,再启动发送类。

发送端代码

    public static void main(String[] args){
        DatagramSocket ds=null;
        DatagramPacket dpSend=null;
        int port=1515;//发送消息到此端口
        try
        {
            ds=new DatagramSocket();
            for(int i=0;i<5;i++)
            {
                byte[] data=("UDP 客户端"+i).getBytes();
                dpSend=new DatagramPacket(data,data.length,InetAddress.getByName("127.0.0.1"),port);
                ds.send(dpSend);
                Thread.sleep(1000);
            }
            ds.close();
        }
        catch(IOException | InterruptedException e)
        {

            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
    }

接收端代码

public static void main(String[] args) throws SocketException {
        int port=1515;//接收此端口消息
        DatagramSocket socket= new DatagramSocket(port);
        System.out.println("UDP服务器已启动.....");
        byte[] buffer = new byte[8192];
        while (true) {
            if(socket.isClosed()){
                System.out.println("UDP已关闭");
            }
            DatagramPacket incoming = new DatagramPacket(buffer,
                    buffer.length);
            try {
                socket.receive(incoming);
                String msg = new String(incoming.getData(),0,incoming.getLength());
                System.out.println("发送端发送的内容是:" + msg);
                System.out.println("发送端IP:" + incoming.getAddress());
                System.out.println("发送端端口:" + incoming.getPort());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

发送端发送消息到远程服务器得某个端口下, 远程服务器的接收端接收此端口下得消息并解析。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值