zoukankan      html  css  js  c++  java
  • java中socket发送数据接收数据(udp)

    /*
     *  java socket send and receice demo
     *  @author:luowen
     *  @time:2013-11-1
     * */
    
    import java.net.*;
    
    class SocketSend
    {
        public static void main(String[] args)throws Exception
        {
            //创建socket服务
            DatagramSocket ds = new DatagramSocket();
    
            byte[]  buf = "yes iam demo".getBytes();
            //构造数据包
            DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("127.0.0.1"),1000);
            //发送数据包
            ds.send(dp);
    
            ds.close();
        }
    }
    
    
    class SocketRece
    {
        public static void main(String[] args)throws Exception
        {
    
            //创建socket服务 坚挺1000端口
            DatagramSocket ds = new DatagramSocket(1000);
    
            byte[] by = new byte[1024];
            DatagramPacket dp = new DatagramPacket(by,by.length);
            //接受
            ds.receive(dp);
    
            String str = "ip:" + dp.getAddress().toString() + "port:" + dp.getPort() + "data:" + new String(dp.getData(),0,dp.getLength());
    
            System.out.println(str);
    
            ds.close();
        }
    }
    

      

  • 相关阅读:
    SpringBoot详细研究-01基础
    JDK1.8快速入门
    海外酒店业务学习
    NOSQL快速入门
    移动前端技术快速入门
    Spring快速入门
    Java基础组件快速入门
    JavaWeb快速入门
    TLS 与 python thread local
    python 类修饰器
  • 原文地址:https://www.cnblogs.com/luowen/p/3403376.html
Copyright © 2011-2022 走看看