精华内容
参与话题
问答
  • UDP 广播发送和接收

    千次阅读 2018-12-03 09:31:34
    // 接收端 #include <iostream> #include <stdio.h> #include <sys/socket.h> #include <unistd.h> #include <sys/types.h> #include &...
    // 接收端
     
    #include <iostream>
    #include <stdio.h>
    #include <sys/socket.h>
    #include <unistd.h>
    #include <sys/types.h>
    #include <netdb.h>
    #include <netinet/in.h>
    #include <arpa/inet.h>
    #include <string.h>
     
     
    using namespace std;
     
    int main()
    {
    	// 绑定地址
    	struct sockaddr_in addrto;
    	bzero(&addrto, sizeof(struct sockaddr_in));
    	addrto.sin_family = AF_INET;
    	addrto.sin_addr.s_addr = htonl(INADDR_ANY);
    	addrto.sin_port = htons(6000);
    	
    	// 广播地址
    	struct sockaddr_in from;
    	bzero(&from, sizeof(struct sockaddr_in));
    	from.sin_family = AF_INET;
    	from.sin_addr.s_addr = htonl(INADDR_ANY);
    	from.sin_port = htons(6000);
    	
    	int sock = -1;
    	if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1) 
    	{   
    		cout<<"socket error"<<endl;	
    		return false;
    	}   
     
    	if(bind(sock,(struct sockaddr *)&(addrto), sizeof(struct sockaddr_in)) == -1) 
    	{   
    		cout<<"bind error..."<<endl;
    		return false;
    	}
     
    	int len = sizeof(sockaddr_in);
    	char smsg[100] = {0};
     
    	while(1)
    	{
    		//从广播地址接受消息
    		int ret=recvfrom(sock, smsg, 100, 0, (struct sockaddr*)&from,(socklen_t*)&len);
    		if(ret<=0)
    		{
    			cout<<"read error...."<<sock<<endl;
    		}
    		else
    		{		
    			cout<<smsg<<endl;	
    		}
     
    		sleep(1);
    	}
     
    	return 0;
    }
    

     

    // 发送端
    
    #include <iostream>
    #include <stdio.h>
    #include <sys/socket.h>
    #include <unistd.h>
    #include <sys/types.h>
    #include <netdb.h>
    #include <netinet/in.h>
    #include <arpa/inet.h>
    #include <string.h>
     
    using namespace std;
     
    int main()
    {
    	int sock = -1;
    	if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1) 
    	{   
    		cout<<"socket error"<<endl;	
    		return false;
    	}   
    	
    	const int opt = 1;
    	//设置该套接字为广播类型,
    	int nb = 0;
    	nb = setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (char *)&opt, sizeof(opt));
    	if(nb == -1)
    	{
    		cout<<"set socket error..."<<endl;
    		return false;
    	}
     
    	struct sockaddr_in addrto;
    	bzero(&addrto, sizeof(struct sockaddr_in));
    	addrto.sin_family=AF_INET;
    	addrto.sin_addr.s_addr=htonl(INADDR_BROADCAST);
    	addrto.sin_port=htons(6000);
    	int nlen=sizeof(addrto);
     
    	while(1)
    	{
    		sleep(1);
    		//从广播地址发送消息
    		char smsg[] = {"abcdef"};
    		int ret=sendto(sock, smsg, strlen(smsg), 0, (sockaddr*)&addrto, nlen);
    		if(ret<0)
    		{
    			cout<<"send error...."<<ret<<endl;
    		}
    		else
    		{		
    			cout<<"ok"<<endl;	
    		}
    	}
     
    	return 0;
    }
    

     

     

    c++类

    #ifndef UDP_BROADCAST_H
    #define UDP_BROADCAST_H
    
    #include <iostream>
    #include <stdio.h>
    #include <sys/socket.h>
    #include <unistd.h>
    #include <sys/types.h>
    #include <netdb.h>
    #include <netinet/in.h>
    #include <arpa/inet.h>
    #include <string.h>
    
    #define UDP_BROADCAST_PORT 6666
    
    using namespace std;
    
    class UdpBroadcast
    {
    public:
        ///
        /// \brief UdpBroadcast
        ///
        UdpBroadcast();
    
        ~UdpBroadcast();
    
        ///
        /// \brief open
        /// \return
        ///
        bool Open();
    
        int BroadcastData(const char* str);
    
        ///
        /// \brief 关闭监听
        ///
        void Close();
    
        ///
        /// \brief IsOpened
        /// \return
        ///
        bool IsOpened() {
            return isOpened;
        }
    
    private:
        int sockfd;
        sockaddr_in dest;
        int chilen;
        bool isOpened;
    };
    
    #endif // UDP_BROADCAST_H
    
    
    
    #include "udpbroadcast.h"
    #include <fcntl.h>
    
    UdpBroadcast::UdpBroadcast() :
        isOpened(false)
    {
        sockfd = -1;
    }
    
    UdpBroadcast::~UdpBroadcast()
    {
        this->Close();
    }
    
    bool UdpBroadcast::Open()
    {
        if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
        {
            cout<<"socket error"<<endl;
            close(sockfd);
            return false;
        }
    
        fcntl(sockfd, F_SETFD, FD_CLOEXEC);///< 子进程不继承该描述符
    
        const int opt = 1;
        //设置该套接字为广播类型,
        int nb = 0;
        nb = setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, (char *)&opt, sizeof(opt));
        if(nb != 0)
        {
            cout<<"set socket error..."<<endl;
            close(sockfd);
            return false;
        }
    
        bzero(&dest, sizeof(struct sockaddr_in));
        dest.sin_family = AF_INET;
        dest.sin_addr.s_addr = htonl(INADDR_BROADCAST);
        dest.sin_port = htons(UDP_BROADCAST_PORT);
        isOpened = true;
        return true;
    }
    
    int UdpBroadcast::BroadcastData(const char *str)
    {
        if(!isOpened)
            return -1;
    
        //从广播地址发送消息
        chilen = sizeof(dest);
        int ret=sendto(sockfd, str, strlen(str), 0, (sockaddr*)&dest, chilen);
    
        if(ret<0)
        {
            perror("send error....");
            isOpened = false;
            close(sockfd);
            return ret;
        }
        else
        {
            cout<<"send data is : "<< str<<" len : "<<strlen(str)<<" sockfd : "<<sockfd<<endl;
        }
    }
    
    void UdpBroadcast::Close()
    {
        if(isOpened) {
            isOpened = false;
            close(sockfd);
        }
    }

     

    展开全文
  • 软件在启动后,准备接收硬件的广播信号,与新风硬件绑定,握手。然后,实现软件硬件的点对点的通信。private int udpPort = 5668; //硬件那说好的端口 private InetAddress group; private MulticastSocket socket...

    先说下实现效果和背景。软件在启动后,准备接收硬件的广播信号,与新风硬件绑定,握手。然后,实现软件和硬件的点对点的通信。

    private int udpPort = 5668; //硬件那说好的端口
    private InetAddress group;
    private MulticastSocket socket;
    private DatagramPacket packet;
    byte[] buf = new byte[1024];
    
    
    static InetAddress inetAddress = null;
    
    private boolean isHasIntenet = false;//用来标记当前是否有网络
    

    然后:

    public void onCreate(Bundle savedInstanceState) {
    
    //首先一个线程,先看有没有连接网络,如果没有连接网络肯定就没必要接收广播,没有发送消息的必要了
        new Thread() {
            public void run() {
                    try {
                    Thread.sleep(5000);
                        final String current_ssid = WifiUtility
                            .get_connected_ssid().replace("\"", "");
    
        //wifi是否能有连接上
            if (current_ssid != null && current_ssid.length() > 0) {
    final String current_ip = WifiUtility.get_wifi_ip();
    // 有网再发送
    isHasIntenet = true;
    new MulReceiverIP().start();
    
                            }
    
    
                } catch (Exception e) {
    
    
                }
    
            }
        }.start();
    
    
        res = getActivity().getResources();
        super.onCreate(savedInstanceState);
    
        }
    
    //这就是接收广播的地方
    
    public class MulReceiverIP extends Thread {
    
    
        public MulReceiverIP() {
            try {
                socket = new MulticastSocket(udpPort);
                group = InetAddress.getByName("230.0.0.0");
                socket.joinGroup(group);
                packet = new DatagramPacket(buf, buf.length);
    
    
            } catch (IOException e) {
                e.printStackTrace();
        }
    
    }
    
    
    public void run() {
    
    
        while (!exitThread) {
    
    
                            try {
                                socket.receive(packet);
    
    
                                } catch (IOException e) {
                        e.printStackTrace();
            }
    
    
            inetAddress = packet.getAddress();
    
            String message = new String(packet.getData(), 0,
            packet.getLength());
    
    
            chargeUdpMessage(message);//写个方法,来处理服务器来的数据
            }
        }
    
    
    }
    
    //操作服务器端的数据
    
    private void chargeUdpMessage(String udpMsg) {
    
    
            String info = (String) udpMsg;
            if (info.contains("Lu_Ca")) {// 叫我呢
                Log.i("I'm here", "I'm here" + info + "进入呼叫");
    
                sendUDPMessage("I'm here");//回应服务器我在,可以发送数据
            } else if (info.contains("wind0")) {//如果服务器端来的数据中有wind0,表示控制风速为0挡
                Message m = new Message();
                m.what = 0;
                ControlFragment.h.sendMessage(m);
            } else if (info.contains("wind1")) {//如果服务器端来的数据中有wind1,表示控制风速为1挡
                Message m = new Message();
                m.what = 1;
                ControlFragment.h.sendMessage(m);
            } else if (info.contains("wind2")) {//如果服务器端来的数据中有wind2,表示控制风速为2挡
                Message m = new Message();
                m.what = 2;
                ControlFragment.h.sendMessage(m);
            } else if (info.contains("wind3")) {//如果服务器端来的数据中有wind3,表示控制风速为3挡
                Message m = new Message();
                m.what = 3;
                ControlFragment.h.sendMessage(m);
            }
    
    }
    
    
    
    // 发送 udp message
    
    
    private void sendUDPMessage(String message) {
    
        //有地址才能发送,不然没有地址,发送就崩溃
        if (inetAddress == null) {
            return;
            }
    
    
        int message_length = message.length();
        byte[] messageByte = message.getBytes();
    
    
        DatagramPacket p = new DatagramPacket(messageByte, message_length,
        inetAddress, udpPort);
    
    
        try {
            socket.send(p);
    
    
            } catch (IOException e) {
        // TODO Auto-generated catch block
            e.printStackTrace();
            }
    }
    
    
    
    //到主线程更改ui界面显示
    
    public static Handler h = new Handler() {
        public void handleMessage(Message msg) {
    
    
                if (msg.what == 0)// 接收关闭新风
    
                {
    
                    wind_speed_image
    
                        .setBackground(res
    
            .getDrawable(R.drawable.new_wind_speed_close_image_new));
    
    
        return;
    
            } else if (msg.what == 1)// 接收新风低风
    
            {
    
                wind_speed_image.setBackground(res
    
    .getDrawable(R.drawable.new_wind_speed_low_image_new));
    
                return;
    
            } else if (msg.what == 2)// 接收新风中风
            {
                wind_speed_image
                .setBackground(res
        .getDrawable(R.drawable.new_wind_speed_middle_image_new));
            return;
            } else if (msg.what == 3)// 接收新风高风
            {
                wind_speed_image
                .setBackground(res
        .getDrawable(R.drawable.new_wind_speed_heigh_image_new));
                return;
            }
        }
    };
    
    展开全文
  • 局域网下UDP广播发送接收

    千次阅读 2017-10-22 18:07:15
    局域网下UDP广播 发送接收

    1.接收udp广播的线程

    private void receiverUdpBroadCast(){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    byte[] buffer = new byte[1024];
                    MulticastSocket server = null;
                    try {
                        server = new MulticastSocket (port);
                        InetAddress ip = InetAddress.getByName(BROADCAST_IP);
                        server.joinGroup(ip);
                        final DatagramPacket packet = new DatagramPacket(buffer,buffer.length);
                        while(true){
                            try {
                                server.receive(packet);
                                final String s = new String(packet.getData(), 0, packet.getLength(), "UTF-8");
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        str.append("收到数据:"+s+",address:"+packet.getAddress()+"\n");
    //                                    Toast.makeText(MainActivity.this,"收到数据啦:"+s,Toast.LENGTH_SHORT).show();
                                    }
                                });
                                System.out.println("address : " + packet.getAddress() + ", port : " + packet.getPort() + ", content : " + s);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    } catch (SocketException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally{
                        if(server != null)
                            server.close();
                    }
                }
            }).start();
        }
    

    2.发送UDP广播线程

    private void sendBroadCastToCenter(){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    WifiManager wifiMgr = (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                    WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
                    /*这里获取了IP地址,获取到的IP地址还是int类型的。*/
                    int ip = wifiInfo.getIpAddress();
                    /*这里就是将int类型的IP地址通过工具转化成String类型的,便于阅读
                    String ips = Formatter.formatIpAddress(ip);
                    */
                    /*这一步就是将本机的IP地址转换成xxx.xxx.xxx.255*/
                    int broadCastIP = ip | 0xFF000000;
                    Log.d("bbbb","broadCastIP:"+broadCastIP);
                    MulticastSocket theSocket = null;
                    try {
                        String ipAddress = Formatter.formatIpAddress(broadCastIP);
                        Log.d("bbbb","ipAddress:"+ipAddress);
                        InetAddress server = InetAddress.getByName(BROADCAST_IP);
                        theSocket = new MulticastSocket(port);
                        theSocket.joinGroup(server);
                        theSocket.setLoopbackMode(false);
                        String data = "Helloaaa";
                        DatagramPacket theOutput = new DatagramPacket(data.getBytes(), data.length(), server, port);
                    /*这一句就是发送广播了,其实255就代表所有的该网段的IP地址,是由路由器完成的工作*/
                        theSocket.send(theOutput);
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        if (theSocket != null)
                            theSocket.close();
                    }
                }
            }).start();
    
        }
    

    实际开发中在同一局域网下,可每隔三秒可发一次udp包,接收线程先于发送线程启动

    展开全文
  •  Udp广播消息用在局域网的消息传递很方便。本文使用UdpClient类在WPF下实现Udp广播收发 发送: 1 void MainWindow_Loaded(object sender, RoutedEventArgs e) 2 { 3 Loaded -= MainWindow_Loaded; 4 ...

    简介:

      Udp广播消息用在局域网的消息传递很方便。本文使用UdpClient类在WPF下实现Udp广播收发

    发送:

     1         void MainWindow_Loaded(object sender, RoutedEventArgs e)
     2         {
     3             Loaded -= MainWindow_Loaded;
     4             UdpClient client = new UdpClient(new IPEndPoint(IPAddress.Any, 0));
     5             IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse("255.255.255.255"), 7788);//默认向全世界所有主机发送即可,路由器自动给你过滤,只发给局域网主机
     6             String ip = "host:" + Dns.GetHostEntry(Dns.GetHostName()).AddressList.Last().ToString();//对外广播本机的ip地址
     7             byte[] ipByte = Encoding.UTF8.GetBytes(ip);
     8             DispatcherTimer dt = new DispatcherTimer() { Interval = TimeSpan.FromSeconds(1) };//每隔1秒对外发送一次广播
     9             dt.Tick += delegate
    10             {
    11                 client.Send(ipByte, ipByte.Length, endpoint);
    12             };
    13             dt.Start();
    14         }


    接收:

     1         void MainWindow_Loaded(object sender, RoutedEventArgs e)
     2         {
     3             Loaded -= MainWindow_Loaded;
     4             UdpClient client = new UdpClient(new IPEndPoint(IPAddress.Any, 7788));//端口要与发送端相同
     5             Thread thread = new Thread(receiveUdpMsg);//用线程接收,避免UI卡住
     6             thread.IsBackground = true;
     7             thread.Start(client);
     8         }
     9         void receiveUdpMsg(object obj)
    10         {
    11             UdpClient client = obj as UdpClient;
    12             IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, 0);
    13             while (true)
    14             {
    15                 client.BeginReceive(delegate(IAsyncResult result) {
    16                     Console.WriteLine(result.AsyncState.ToString());//委托接收消息
    17                 }, Encoding.UTF8.GetString(client.Receive(ref endpoint)));
    18             }
    19         }


    效果:

     

     

      

     
     

    转载于:https://www.cnblogs.com/JimmyBright/p/4637090.html

    展开全文
  • socket UDP广播发送和接收示例

    千次阅读 2019-04-11 09:47:01
    网络通信基础 如果网络中两个主机上的应用程序要相互通信,其一要知道彼此的IP,其二要知道程序可监听的端口。因为同一主机上的程序使用网络是通过端口号来区分的。...4. 发送接收数据。 5. 销毁套接字。...
  • // 发送端 #include #include #include #include #include #include #include #include #include using namespace std; int main() { setvbuf(stdout, NULL, _IONBF, 0); fflush(stdout); int ...
  • Netty的UDP广播发送接收

    千次阅读 2019-08-09 20:03:54
    A向局域网内发送广播消息messageA; B收到了messageA并直接使用既有的session或channel把需要回复的消息write回来就行了。 自己尝试了一下,记载一下使用中较为便利的写法。 客户端一般是这样写: EventLoopGroup ...
  • JAVA之UDP广播接收发送小程序

    千次阅读 2016-07-27 19:57:35
    接收者 import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.FlowLayout; import java.awt.Graphics; import java.awt.Point; import java.awt.Window; import java...
  • UDP广播接收,用于局域网内多台设备之间的通信
  • Java网络编程笔记启用UDP广播发送下通信编程//发送端代码 import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net....
  • public class UdpBroadcast {private int iReceivePort = 0; //接收到消息的端口号private static final int TIMEOUT = 200;... //服务器返回的消息/** * udp广播 */public String doUdpFind(Strin
  • Android发送和接收UDP广播

    万次阅读 2017-08-02 11:07:29
    在Android平台上实现UDP广播发送和接收
  • Linux下UDP广播发送接受

    千次阅读 2019-05-06 21:22:48
    网络通信基础 如果网络中两个主机上的应用程序要相互通信,其一要知道彼此的IP,其二要知道程序可监听的端口。因为同一主机上的程序使用...UDP Socket的使用过程: 1. 初始化网络库 2. 创建SOCK_DGRAM类型的Soc...
  • C语言socket UDP广播发送和接收示例

    万次阅读 2014-04-28 22:14:07
    server.c通过UDP广播的形式向网段的指定端口发送广播信息 client.c绑定到指定端口,并阻塞接收广播内容然后打印出来 程序非常简单,不过有一点需要注意,那就是setsockopt()函数的使用。使用不当很可能会出问题。...
  • UDP广播与多播

    千次阅读 2018-10-28 13:43:01
    一、UDP广播 1、广播的概念   使用UDP协议进行信息的传输之前不需要建议连接。换句话说就是客户端向服务器发送信息,客户端只需要给出服务器的ip地址端口号,然后将信息封装到一个待发送的报文中并且发送出去...
  • 用Java语言实现udp广播编程

    千次阅读 2018-04-22 15:28:07
    发送方程序:import java.io.IOException;import java.net.DatagramPacket;import java.net.InetAddress;import java.net.MulticastSocket;public class BrodecastSend { public static void main(String[] args) ...
  • udp广播发送接收

    2016-04-08 10:30:37
    用于udp的广播与接收。一方发送udp广播,收到广播的客户端将会返回一个广播。发送端读取这个广播中的IP
  • //广播接收 MulticastSocket multicastSocket1 = null; InetAddress inetAddress1 = null; String str=""; private void acceptBroadCast() { new Thread(new Runnable() { @Override public void ...
  • Qt UDP 广播简单示例

    千次阅读 2017-12-03 19:09:16
    前言用 Qt 的 UDP 来实现一个广播示例,代码其实非常简单,需要用到 QUdpSocket 类,这里实现两个工程,服务端客户端,由服务器端发送广播消息到每个客户端接收显示。正文先来看看两个示例的运行图片 左边是...
  • VC UDP接收 发送 广播

    2020-11-05 12:19:09
    win程序,button1单击向192.168.168.255发送字符串:"{"Cmd":"GetDeviceInfo"}" ARM板收到返回设备信息 ARM板上程序打印信息: VC代码: 全局变量 int UDP_Sock_FD = -1;// 套接字 struct sockaddr_in ...
  • 网络UDP广播包发不出去或接收不到问题

    万次阅读 多人点赞 2014-12-03 14:59:33
    在公司最近项目中,有关设备搜索采用UDP广播方式搜索,出现的情况是,部分机器能正常接收到广播包,部分机器接收不到广播包,部分机器发送不了广播包情况,经过N天的查询,结果发现惊人的秘密:虚拟机网卡导致广播包...
  • MFC的UDP广播实验程序

    热门讨论 2012-07-24 14:12:28
    MFC程序,UDP广播交互试验平台,获取本机MAC,获取本机主机名,获取发送广播主机的IP。
  • 使用UDP实现数据通信,网上大多采用客户接收服务端分离的方式,该程序代码为了方便采用线程的方式写在一个MFC程序中,方便大家初学时学习。调试环境:win7 64 vs2010.
  • unityUDP广播

    2020-08-14 18:07:58
    udp广播代码, private UdpClient m_udpClient; private IPEndPoint endPoint; private IPEndPoint m_ipEndPoint; private IPAddress m_UpdReceiveDataIP; 创建UDP客户端: public void CreatUDP() { m_udpClient ...
  • python3 udp 广播 源码

    万次阅读 2018-09-09 09:46:57
    udp广播 *************************************************** from socket import * s=socket(AF_INET,SOCK_DGRAM) s.setsockopt(SOL_SOCKET,SO_...
  • LwIP实现UDP广播接收

    千次阅读 2012-03-04 15:24:27
    #include "lwip/opt.h" #include "lwip/sys.h" #include "lwip/sockets.h" #define RCV_BUFFER_LEN 1024  unsigned char rec_buffer[RCV_BUFFER_LEN]={"\n"};  ...unsigned char rec_buffer1[R
  • python之udp广播

    2019-12-01 00:25:55
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)# ...#对这个需要发送广播数据的套接字进行修改设置,否则不能发送广播数据 s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) #允许s发送广播数据 ...
  • 电脑收不到UDP广播

    千次阅读 2019-02-26 11:16:28
    在同一个局域网里本机电脑上无法收到终端UDP的广播,而其他电脑能接收到,可以查看一下自己电脑上是否存在虚拟网卡启动了,如有把他禁用,因为UDP广播的信息会被拦截。       ...
  • UDP广播发送和接收的VC程序

    热门讨论 2014-11-26 10:37:50
    UDP广播发送和接收的VC程序,包含注释,UDP广播也算是UDP传输的基础知识,本程序为本人自己编写,也经过调试。

空空如也

1 2 3 4 5 ... 20
收藏数 70,330
精华内容 28,132
关键字:

udp广播接收和发送