zoukankan      html  css  js  c++  java
  • 网络通信1_UDP通信程序

    • 案例需求

    UDP发送数据:数据来自于键盘录入,直到输入的数据是886,发送数据结束

    UDP接收数据:因为接收端不知道发送端什么时候停止发送,故采用死循环接收

    发送端:

    public class UDP_SendDemo {
    public
    static void main(String[] args) throws IOException { //创建发送端的Socket对象(DatagramSocket) DatagramSocket ds= new DatagramSocket(); //自己封装键盘录入数据 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line; while((line=br.readLine())!=null){ //输入数据是886,发送数据结束 if("886".equals(line)){ break; } byte[] bys=line.getBytes(); DatagramPacket dp =new DatagramPacket(bys,bys.length, InetAddress.getByName("153.13.73.101"),12345); //调用DatagramSocket对象发送数据 ds.send(dp); } //关闭发送端 ds.close(); } }
    }

    接收端:

    public class UDP_ReceiveDemo {
        public static void main(String[] args) throws IOException {
            DatagramSocket ds = new DatagramSocket(12345);
            while(true){
                //创建一个数据包,用于接收数据
                byte[] bys = new byte[1024];
                DatagramPacket dp=new DatagramPacket(bys,bys.length);
                //调用DatagramSocket对象的方法接收数据
                ds.receive(dp);
                System.out.println("数据是:"+new String(dp.getData(),0,dp.getLength()));
                //关闭接收端
                ds.close();
            }
        }
    }
  • 相关阅读:
    php 小试 mysql-zmq-plugin 和 pthreads
    svn:previous operation has not finished
    Http Header里的Content-Type
    sublime text使用及常见问题
    Less:优雅的写CSS代码
    gulp:更简单的自动化构建工具
    js实现『加载更多』功能实例
    JSONP浅析
    使用JSSDK集成微信分享遇到的一些坑
    JavaScript模板引擎实例应用
  • 原文地址:https://www.cnblogs.com/newway644617704/p/14193876.html
Copyright © 2011-2022 走看看