udp客户端广播

2019-07-12  本文已影响0人  招风小妖怪
package uuu;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

/***
 * UDPclientClient端
 ***/
public class UdpClient {
   
    private static DatagramSocket datagramSocket;
    private static DatagramPacket datagramPacket;
   
    public static void createConnect()
    {
        
        // 初始化datagramSocket,注意与前面Server端实现的差别          
        try {
            datagramSocket = new DatagramSocket();
        } catch (SocketException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public static void send(String str,String ip,int port)
    {
        
        byte[] buf = str.getBytes();
        InetAddress address = null;
        try {
            address = InetAddress.getByName(ip);
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        datagramPacket = new DatagramPacket(buf, buf.length, address, port);
        // 发送数据
        try {
            datagramSocket.send(datagramPacket);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public static void main(String[] args){
           createConnect();
           send("hello world","255.255.255.255",8181);
                 
            new Thread(){                               //1.继承Thread类
                public void run(){                      //2.重写run()方法
                    /*** 接收数据***/
                    while(true){
                        
                        byte[] receBuf = new byte[1024];
                        DatagramPacket recePacket = new DatagramPacket(receBuf, receBuf.length);                                                
                            try {
                                datagramSocket.receive(recePacket);
                                String receStr = new String(recePacket.getData(), 0 , recePacket.getLength());
                                System.out.println("收到数据::" + receStr);
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }                                                                       
                    }
                }
            }.start(); 

           
    }  
}


上一篇下一篇

猜你喜欢

热点阅读