您的位置:首页 > 其它

Boost_udp错误

2016-02-26 11:35 246 查看
 

注意一点:当我们不同PC机间进行通信的时候,IP和端口号是不一样的。之前遇到的问题是,boost_system_error,这是因为我们在写程序的时候,发送和接收绑定了同一个端口,导致程序出错。

而且,CANET支持组播通信,也就是说,一个通道可以同时向多个端口发送数据。

 

之前一直搞错的原因就是端口重复绑定了,导致错误。



/*

* Copyright (c) 2015,北京智行者科技有限公司

* All rights reserved.

*

* 文件名称:Boost_UDP.h

* 文件标识:见软件框架协议

* 摘 要:UDP读写类

*

* 当前版本:1.0

* 作 者:zhuxuekui

* 完成日期:2015年11月30日

* 修 改:

*

* 取代版本:1.0

* 原作者 :zhuxuekui

* 完成日期:2015年11月30日

*/

 
#ifndef BOOST_UDP_H

#define BOOST_UDP_H

 
#include "Utils.h"

 
using
namespace boost;

 
#define RECVSIZE 1024

class Boost_UDP

{

public:

 
   Boost_UDP(boost::asio::io_service &io_service,string pcIP, int pcPort, string canetIP, int canetPort):udp_sock(io_service)

   {

       m_canetIP = canetIP;

      m_canetPort = canetPort;

      m_pcIP = pcIP;

      m_pcPort = pcPort;

   }

 
   ~Boost_UDP()

   {

      udp_sock.close();

   }

 
   //开始socket,绑定端口等。 绑定PC机端口号,而且还不能用 127.0.0.1, 不然会出错,很奇怪的原因。

   void start_sock()

   {

      // here the ip can change to 192.168.1.33

       boost::asio::ip::udp::endpoint local_add(boost::asio::ip::address_v4::from_string(m_pcIP),m_pcPort);

      udp_sock.open(local_add.protocol());

      udp_sock.bind(local_add);

   }

 
   //收数据

   int receive_data(unsigned char buf[])

   {

      boost::mutex::scoped_lock lock(mutex);

       //donot change 目的端口与发送端口现在是不一样的

       boost::asio::ip::udp::endpoint send_endpoint(boost::asio::ip::address_v4::from_string(m_pcIP),m_pcPort); //这里的endpoint是PC机的IP和端口号

       int ret = udp_sock.receive_from(boost::asio::buffer(buf,RECVSIZE),send_endpoint);//堵塞模式

      return ret;

   }

 
   //发送数据

   int send_data(unsigned char str[], int len)

   {

      boost::mutex::scoped_lock lock(mutex);

      //donot change

      boost::asio::ip::udp::endpoint send_endpoint(boost::asio::ip::address_v4::from_string(m_canetIP),m_canetPort); //canet的IP和端口号

      int ret = udp_sock.send_to(boost::asio::buffer(str,len),send_endpoint);

      return ret;

   }

public:

 
   string m_canetIP;

   int m_canetPort;

   string m_pcIP;

   int m_pcPort;

 
   boost::asio::ip::udp::socket udp_sock;

   mutable boost::mutex mutex;

 
};

 

 
#endif
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: