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
相关文章推荐
- 单页面应用SPA架构
- Implement Stack using Queues
- iOS怎样将 URL转换成String
- Eclipse 搭建 struts2 spring mybitas 框架
- awk循环处理文本进行统计
- flash初探
- C#关键字:yield
- Xcode7--免证书真机调试
- java 和js中的math.floor()方法
- SDN南向接口和北向接口区别
- 多服务器管理工具fablinker
- AIDL
- 前端【网站集锦】
- 关于python django-admin.py startproject mysite不工作的问题
- CSS hack
- 【POJ 2482】 Stars in Your Window(线段树+离散化+扫描线)
- how to setup php running environment on osx
- C# 值类型与引用类型 (上)
- Pomelo 新手计划(四)
- Puppet自动化工具工作原理介绍