Mongodb在windows的安装

本文是描述Mongodb3.6在windows10的下的安装,下面的所有步骤都是在cmd运行

下载Mongodb安装包

下载地址:https://www.mongodb.com/download-center,运行安装

管理员运行cmd

按键盘win按键,cmd 然后右键管理员运行

创建目录(数据库和日志目录)

mkdir c:\data\db
mkdir c:\data\log

创建配置文件mongod.cfg

systemLog:
    destination: file
    path: c:\data\log\mongod.log
storage:
    dbPath: c:\data\db

安装Mongodb服务

"C:\Program Files\MongoDB\Server\3.6\bin\mongod.exe" --config "C:\Program Files\MongoDB\Server\3.6\mongod.cfg" --install

启动Mongodb服务

net start MongoDB

停止或者删除Mongodb服务

net stop MongoDB
"C:\Program Files\MongoDB\Server\3.6\bin\mongod.exe" --remove

策略模式与命令模式比较及实现

定义

Strategy策略模式 把易于变化的行为分别封装起来,让它们之间可以互相替换, 让这些行为的变化独立于拥有这些行为的客户。
GoF《设计模式》中说道:定义一系列算法,把它们一个个封装起来,并且使它们可以相互替换。该模式使得算法可独立于它们的客户变化。

Command命令模式是一种对象行为型模式,它主要解决的问题是:在软件构建过程中,“行为请求者”与“行为实现者”通常呈现一种“紧耦合”的问题。
GoF《设计模式》中说道:将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤销的操作。

区别

命令模式是含有不同的命令(含有接收者的请求):做不同的事情;隐藏接收者执行细节。常见菜单事件,
而策略模式含有不同的算法,做相同的事情;
区别在于是否含有接收者。命令模式含有,策略模式不含有。

c++代码

策略模式

#include <iostream.h>
#include <fstream.h>
#include <string.h>

class Strategy;

class TestBed
{
  public:
    enum StrategyType
    {
        Dummy, Left, Right, Center
    };
    TestBed()
    {
        strategy_ = NULL;
    }
    void setStrategy(int type, int width);
    void doIt();
  private:
    Strategy *strategy_;
};

class Strategy
{
  public:
    Strategy(int width): width_(width){}
    void format()
    {
        char line[80], word[30];
        ifstream inFile("quote.txt", ios::in);
        line[0] = '\0';

        inFile >> word;
        strcat(line, word);
        while (inFile >> word)
        {
            if (strlen(line) + strlen(word) + 1 > width_)
              justify(line);
            else
              strcat(line, " ");
            strcat(line, word);
        }
        justify(line);
    }
  protected:
    int width_;
  private:
    virtual void justify(char *line) = 0;
};

class LeftStrategy: public Strategy
{
  public:
    LeftStrategy(int width): Strategy(width){}
  private:
     /* virtual */void justify(char *line)
    {
        cout << line << endl;
        line[0] = '\0';
    }
};

class RightStrategy: public Strategy
{
  public:
    RightStrategy(int width): Strategy(width){}
  private:
     /* virtual */void justify(char *line)
    {
        char buf[80];
        int offset = width_ - strlen(line);
        memset(buf, ' ', 80);
        strcpy(&(buf[offset]), line);
        cout << buf << endl;
        line[0] = '\0';
    }
};

class CenterStrategy: public Strategy
{
  public:
    CenterStrategy(int width): Strategy(width){}
  private:
     /* virtual */void justify(char *line)
    {
        char buf[80];
        int offset = (width_ - strlen(line)) / 2;
        memset(buf, ' ', 80);
        strcpy(&(buf[offset]), line);
        cout << buf << endl;
        line[0] = '\0';
    }
};

void TestBed::setStrategy(int type, int width)
{
  delete strategy_;
  if (type == Left)
    strategy_ = new LeftStrategy(width);
  else if (type == Right)
    strategy_ = new RightStrategy(width);
  else if (type == Center)
    strategy_ = new CenterStrategy(width);
}

void TestBed::doIt()
{
  strategy_->format();
}

int main()
{
  TestBed test;
  int answer, width;
  cout << "Exit(0) Left(1) Right(2) Center(3): ";
  cin >> answer;
  while (answer)
  {
    cout << "Width: ";
    cin >> width;
    test.setStrategy(answer, width);
    test.doIt();
    cout << "Exit(0) Left(1) Right(2) Center(3): ";
    cin >> answer;
  }
  return 0;
}

命令模式

#include <iostream>
using namespace std;

#define SAFE_DELETE(p) if (p) { delete p; p = NULL; }

class Receiver
{
public:
     void Action()
     {
          cout<<"Receiver->Action"<<endl;
     }
};

class Command
{
public:
     virtual void Execute() = 0;
};

class ConcreteCommand : public Command
{
public:
     ConcreteCommand(Receiver *pReceiver) : m_pReceiver(pReceiver){}
     void Execute()
     {
          m_pReceiver->Action();
     }
private:
     Receiver *m_pReceiver;
};

class Invoker
{
public:
     Invoker(Command *pCommand) : m_pCommand(pCommand){}
     void Invoke()
     {
          m_pCommand->Execute();
     }
private:
     Command *m_pCommand;
};

int main()
{
     Receiver *pReceiver = new Receiver();
     Command *pCommand = new ConcreteCommand(pReceiver);
     Invoker *pInvoker = new Invoker(pCommand);
     pInvoker->Invoke();
     SAFE_DELETE(pInvoker);
     SAFE_DELETE(pCommand);
     SAFE_DELETE(pReceiver);
     return 0;
}

 

加速github访问克隆

不定期更新ip地址2017 7月8日更新

github的各种问题

针对GitHub.com 打开忙,布局乱,Git clone速度慢到4K ,或者断开
fatal: early EOF
fatal: The remote end hung up unexpectedly
fatal: index-pack failed
git did not exit cleanly (exit code 128)

修改hosts

  • 用文本编辑器打开:%SystemRoot%\System32\drivers\etc\hosts
  • 复制内容上面文件

已失效

# GitHub Start
#151.101.112.249 github.global.ssl.fastly.net
#110.4.24.178    bit.ly
110.4.24.178    github.com
110.4.24.178    raw.githubusercontent.com
110.4.24.178    gist.github.com
110.4.24.178    assets-cdn.github.com
110.4.24.178    avatars0.githubusercontent.com
110.4.24.178    avatars1.githubusercontent.com
110.4.24.178    avatars2.githubusercontent.com
110.4.24.178    avatars3.githubusercontent.com
110.4.24.178    camo.githubusercontent.com
110.4.24.178    cloud.githubusercontent.com
110.4.24.178    collector.githubapp.com
# GitHub End

已失效

# Github start
192.30.255.118  github.global.ssl.fastly.net
192.30.253.118	gist.github.com
# Github end

2017 07 08

192.30.255.112	gist.github.com
151.101.44.249	global-ssl.fastly.net

windows刷新DNS

启动cmd 命令窗口输入:ipconfig/flushdns
Linux的etc/hosts

mysql x64在windows安装

windwos mysql x64版,没提供exe的安装包。

下载mysql x64

选择Windows (x86, 64-bit), ZIP Archive:
https://dev.mysql.com/downloads/mysql/最新版
(trinitycore推荐版本)5.6:https://dev.mysql.com/downloads/mysql/5.6.html#downloads
解压到F盘:F:\mysql-5.6.34-winx64

安装mysql x64

1、在F:\mysql-5.6.34-winx64目录下新建my.ini

[mysqld]

#绑定IPv4和3306端口
bind-address = 0.0.0.0
port = 3306

# 设置mysql的安装目录
basedir=F:/mysql-5.6.34-winx64

# 设置mysql数据库的数据的存放目录
datadir=F:/mysql-5.6.34-winx64/data

# 允许最大连接数
max_connections=200

2、管理员运行cmd进入F:\mysql-5.6.34-winx64\bin:
安装:mysqld -install

mysql 5.7以上的版本必须执行下面的
mysqld --initialize [with random root password] //root 随机密码
mysqld --initialize-insecure [without random root password]//root 空密码

启动:net start mysql
删除:mysqld -remove
3、添加F:\mysql-5.6.34-winx64\bin到环境变量PATH

管理添加用户:

喜欢用命令的用命令,或者图形管理

cocos2d-x安卓静态库

cocos2d-x的新建工程项目重新编译整个引擎,在windows系统下好说,只需要把库指定。android和IOS如果也是每个项目都生成引擎,游戏项目多硬盘空间也吃紧。适用cocos2d3.13 ,3.5版不通过

  1.  首先找到一个cocos2d-x的测试项目(如cpp_test),进行一次编译。完成后,在proj.android/obj/local目录下可以找到中间过程中生成的所有静态库文件。把这些静态库文件(带上ABI目录)复制出来,objs-debug和objs文件夹可删除,放到一个新的目录(如:cclib)中。
  2.  在cclib中创Android.mk文件,文件内容见代码附1.
  3. 新建Windows环境变量 CC_SRC_ROOT 为cocos2d源码目录(即cocos与external的上层目录)
  4. 在编译你的项目时依赖cclib即可,不需要依赖cocos2d目录下的Android.mk 附2

附1(cclib/Android.mk)

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE := cc_static
LOCAL_MODULE_FILENAME := libcc

LOCAL_EXPORT_C_INCLUDES := $(CC_SRC_ROOT)/cocos \
                    $(CC_SRC_ROOT)/cocos/. \
                    $(CC_SRC_ROOT)/cocos/.. \
                    $(CC_SRC_ROOT)/cocos/platform \
                    $(CC_SRC_ROOT)/cocos/base \
					$(CC_SRC_ROOT)/extensions \
                    $(CC_SRC_ROOT)/external \
                    $(CC_SRC_ROOT)/external/tinyxml2 \
                    $(CC_SRC_ROOT)/external/unzip \
                    $(CC_SRC_ROOT)/external/chipmunk/include/chipmunk \
                    $(CC_SRC_ROOT)/external/xxhash \
                    $(CC_SRC_ROOT)/external/nslog \
                    $(CC_SRC_ROOT)/external/poly2tri \
                    $(CC_SRC_ROOT)/external/poly2tri/common \
                    $(CC_SRC_ROOT)/external/poly2tri/sweep \
					$(CC_SRC_ROOT)/cocos/platform/android \
					$(CC_SRC_ROOT)/cocos/audio/include \
					$(CC_SRC_ROOT)/external/curl/include/android \
					$(CC_SRC_ROOT)/external/websockets/include/android \
					$(CC_SRC_ROOT)/cocos/editor-support \
					$(CC_SRC_ROOT)/external/Box2D \
					$(CC_SRC_ROOT)/external/flatbuffers \
					$(CC_SRC_ROOT)/external

LOCAL_CFLAGS   :=  -DUSE_FILE32API -fexceptions

LOCAL_CPPFLAGS := -Wno-deprecated-declarations -Wno-extern-c-compat

LOCAL_EXPORT_CFLAGS   := -DUSE_FILE32API -fexceptions

LOCAL_EXPORT_CPPFLAGS := -Wno-deprecated-declarations -Wno-extern-c-compat

LOCAL_EXPORT_LDLIBS := -lGLESv2 \
                       -llog \
                       -landroid \
               -lGLESv1_CM \
                       -lEGL \
               -lOpenSLES

# define the macro to compile through support/zip_support/ioapi.c


LOCAL_WHOLE_STATIC_LIBRARIES := cocos_freetype2_static
LOCAL_WHOLE_STATIC_LIBRARIES += cocos_png_static
LOCAL_WHOLE_STATIC_LIBRARIES += cocos_jpeg_static
LOCAL_WHOLE_STATIC_LIBRARIES += cocos_tiff_static
LOCAL_WHOLE_STATIC_LIBRARIES += cocos_webp_static
LOCAL_WHOLE_STATIC_LIBRARIES += cocos_chipmunk_static
LOCAL_WHOLE_STATIC_LIBRARIES += cocos_zlib_static
LOCAL_WHOLE_STATIC_LIBRARIES += cocos_curl_static
LOCAL_WHOLE_STATIC_LIBRARIES += websockets_static

LOCAL_WHOLE_STATIC_LIBRARIES += flatbuffers_static
LOCAL_WHOLE_STATIC_LIBRARIES += libaudioengine_static
LOCAL_WHOLE_STATIC_LIBRARIES += libbox2d_static
LOCAL_WHOLE_STATIC_LIBRARIES += libbullet_static
LOCAL_WHOLE_STATIC_LIBRARIES += libcocos2d_static
LOCAL_WHOLE_STATIC_LIBRARIES += libcocos2dandroid_static
LOCAL_WHOLE_STATIC_LIBRARIES += libcocos2dxinternal_static
LOCAL_WHOLE_STATIC_LIBRARIES += libcocos3d_static
LOCAL_WHOLE_STATIC_LIBRARIES += libcocosbuilder_static
LOCAL_WHOLE_STATIC_LIBRARIES += libcocosdenshion_static
LOCAL_WHOLE_STATIC_LIBRARIES += libcocostudio_static
#LOCAL_WHOLE_STATIC_LIBRARIES += libcpufeatures_static
LOCAL_WHOLE_STATIC_LIBRARIES += libextension_static
LOCAL_WHOLE_STATIC_LIBRARIES += libnetwork_static
LOCAL_WHOLE_STATIC_LIBRARIES += librecast_static
LOCAL_WHOLE_STATIC_LIBRARIES += libspine_static
LOCAL_WHOLE_STATIC_LIBRARIES += libui_static

include $(BUILD_STATIC_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE := flatbuffers_static
LOCAL_SRC_FILES := $(TARGET_ARCH_ABI)/flatbuffers.a
include $(PREBUILT_STATIC_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE := libaudioengine_static
LOCAL_SRC_FILES := $(TARGET_ARCH_ABI)/libaudioengine.a
include $(PREBUILT_STATIC_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE := libbox2d_static
LOCAL_SRC_FILES := $(TARGET_ARCH_ABI)/libbox2d.a
include $(PREBUILT_STATIC_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE := libbullet_static
LOCAL_SRC_FILES := $(TARGET_ARCH_ABI)/libbullet.a
include $(PREBUILT_STATIC_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE := libcocos2d_static
LOCAL_SRC_FILES := $(TARGET_ARCH_ABI)/libcocos2d.a
include $(PREBUILT_STATIC_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE := libcocos2dandroid_static
LOCAL_SRC_FILES := $(TARGET_ARCH_ABI)/libcocos2dandroid.a
include $(PREBUILT_STATIC_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE := libcocos2dxinternal_static
LOCAL_SRC_FILES := $(TARGET_ARCH_ABI)/libcocos2dxinternal.a
include $(PREBUILT_STATIC_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE := libcocos3d_static
LOCAL_SRC_FILES := $(TARGET_ARCH_ABI)/libcocos3d.a
include $(PREBUILT_STATIC_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE := libcocosbuilder_static
LOCAL_SRC_FILES := $(TARGET_ARCH_ABI)/libcocosbuilder.a
include $(PREBUILT_STATIC_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE := libcocosdenshion_static
LOCAL_SRC_FILES := $(TARGET_ARCH_ABI)/libcocosdenshion.a
include $(PREBUILT_STATIC_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE := libcocostudio_static
LOCAL_SRC_FILES := $(TARGET_ARCH_ABI)/libcocostudio.a
include $(PREBUILT_STATIC_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE := libcpufeatures_static
LOCAL_SRC_FILES := $(TARGET_ARCH_ABI)/libcpufeatures.a
include $(PREBUILT_STATIC_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE := libextension_static
LOCAL_SRC_FILES := $(TARGET_ARCH_ABI)/libextension.a
include $(PREBUILT_STATIC_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE := libnetwork_static
LOCAL_SRC_FILES := $(TARGET_ARCH_ABI)/libnetwork.a
include $(PREBUILT_STATIC_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE := librecast_static
LOCAL_SRC_FILES := $(TARGET_ARCH_ABI)/librecast.a
include $(PREBUILT_STATIC_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE := libspine_static
LOCAL_SRC_FILES := $(TARGET_ARCH_ABI)/libspine.a
include $(PREBUILT_STATIC_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE := libui_static
LOCAL_SRC_FILES := $(TARGET_ARCH_ABI)/libui.a
include $(PREBUILT_STATIC_LIBRARY)

#==============================================================
$(call import-module,freetype2/prebuilt/android)
$(call import-module,png/prebuilt/android)
$(call import-module,zlib/prebuilt/android)
$(call import-module,jpeg/prebuilt/android)
$(call import-module,tiff/prebuilt/android)
$(call import-module,webp/prebuilt/android)
$(call import-module,chipmunk/prebuilt/android)
$(call import-module,curl/prebuilt/android)
$(call import-module,websockets/prebuilt/android)

附2(cpp-empty-test)

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE := cpp_empty_test_shared

LOCAL_MODULE_FILENAME := libcpp_empty_test

LOCAL_ARM_MODE := arm

LOCAL_SRC_FILES := main.cpp \
                   ../../Classes/AppDelegate.cpp \
                   ../../Classes/HelloWorldScene.cpp

LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes \
                    $(LOCAL_PATH)/../../../../extensions \
                    $(LOCAL_PATH)/../../../.. \
                    $(LOCAL_PATH)/../../../../cocos/editor-support

#LOCAL_STATIC_LIBRARIES := cocos2dx_static
LOCAL_WHOLE_STATIC_LIBRARIES := cc_static
include $(BUILD_SHARED_LIBRARY)

#$(call import-module,.)
$(call import-module,cclib)

参考:http://www.cnblogs.com/leaving/p/5362918.html

unrealengine最新版源代码

获取ue4全部源代码

什么是github?

github是程序员乐园,用来托管开发项目的源代码,基于web。

如何访问github上的ue4源代码

简单的四步骤:
1、创建登录github.com账号
2、注册ue的账号,拼关联github的账号https://www.unrealengine.com/dashboard/settings
ue-github
3、访问UE的地址:http://github.com/EpicGames,看到UE的邀请点击它将会看到
EpicGames
4、用git工具下载开发中的版本,或者下载稳定版https://github.com/EpicGames/UnrealEngine/releases

你需要的源代码

大部分程序员只需安装版本,如果你直接修改UE引擎源代码,那么你是来对地方。
引用网址:https://www.unrealengine.com/ue4-on-github

pokemon go (精灵宝可梦go)

pokemon go是google earth前员工的公司和任天堂合作开发的基于GPS AR(增强现实)手游,支持ISO Android。目前中国区没开放。中文名:精灵宝可梦go

介绍

GPS技术进行定位,想象下走在路上,打开游戏进行精灵战斗。

链接地址

苹果版:https://itunes.apple.com/us/app/pokemon-go/id1094591345?mt=8
安卓版:https://play.google.com/store/apps/details?id=com.nianticlabs.pokemongo

gps signal not found

1、手机设置打开手机GPS
2、安装谷歌地图
3、安装google paly

pokemon go

批量编码转换utf-8

批量转换编码是很痛苦的事情,一种办法是自己去写代码来实现,你得解析判断文件编码的类型utf-8 utf-16 ansi ucs-2,然后判断,难保证都成功的转换。提供一种利用第三方工具批量转换成utf-8 ansi等。

安装nodepad++及插件

  1. 安装https://notepad-plus-plus.org/
  2. Plugins->Plugin Manager->Show Plugin Manager
  3. Python Script安装重启Notepad++
  4. Plugins->Python Script->New script
  5. 输入名字toUtf-8,然后复制下面python脚本
  6. 运行脚本Plugins->Python Script->scripts->toUtf-8

python脚本

转换utf-8、注意备份,是直接把文件编码转换,不支持中文路径

import os;
import sys;
from Npp import notepad #这里必须导入nodepad++ if i note this line, it says, "notepad is not defined"
filePathSrc="E:\\Beyond2\\"#"E:\\Songs2\\" # Path to the folder with files to convert
for root, dirs, files in os.walk(filePathSrc):
    for fn in files:
        if fn[-4:] == '.dtx': # Specify type of the files 判断指定的后缀名
            notepad.open(root + "\\" + fn)
            notepad.runMenuCommand("Encoding", "Convert to UTF-8")#想转成ANSI 替换UTF-8
            notepad.save()
            notepad.close()

 

下一代图像接口-Vulkan教程

Vulkan发布有段时间,经过搜索,暂未发现有用的引导性文章,C++ 版demo教程、例子,我也找了很长的一段时间包括官方的教程,可惜官方的教程有短板。

系统要求

建议winX64 vs2015,作者自述支持Linux android,编译器必须支持c++11,笔者只在win系统做过试验,建议更新最新的显卡驱动。近两年的显卡支持上没问题。

源代码下载

github的下载地址,建议用git 检出,以后方便升级

https://github.com/SaschaWillems/Vulkan/archive/master.zip

游戏引擎支持

unity3d 、Unreal Engine 4、OGRE(图形引擎计划),Urho3D(以后支持)

编译

打开vulkanExamples.sln,设置项目triangle为启动项,按F5,经典三角形渲染

源代码简单解析

分辨率设置

    VulkanExample() : VulkanExampleBase(ENABLE_VALIDATION)
    {
        width = 1280;
        height = 720;
        zoom = -2.5f;
        title = "Vulkan Example - Basic indexed triangle";
        // Values not set here are initialized in the base class constructor
    }

矩阵变换,和GL一样,用了GLM的数学库, MVP(模型矩阵 视图矩阵 投影矩阵)

	void updateUniformBuffers()
	{
		// Update matrices
		uboVS.projectionMatrix = glm::perspective(glm::radians(60.0f), (float)width / (float)height, 0.1f, 256.0f);

		uboVS.viewMatrix = glm::translate(glm::mat4(), glm::vec3(0.0f, 0.0f, zoom));

		uboVS.modelMatrix = glm::mat4();
		uboVS.modelMatrix = glm::rotate(uboVS.modelMatrix, glm::radians(rotation.x), glm::vec3(1.0f, 0.0f, 0.0f));
		uboVS.modelMatrix = glm::rotate(uboVS.modelMatrix, glm::radians(rotation.y), glm::vec3(0.0f, 1.0f, 0.0f));
		uboVS.modelMatrix = glm::rotate(uboVS.modelMatrix, glm::radians(rotation.z), glm::vec3(0.0f, 0.0f, 1.0f));

		// Map uniform buffer and update it
		uint8_t *pData;
		VK_CHECK_RESULT(vkMapMemory(device, uniformDataVS.memory, 0, sizeof(uboVS), 0, (void **)&pData));
		memcpy(pData, &uboVS, sizeof(uboVS));
		vkUnmapMemory(device, uniformDataVS.memory);
	}

渲染

	virtual void render()
	{
		if (!prepared)
			return;
		draw();
	}

triangle

boost asio广播

一篇boost asio UDP广播示例。

为什么要广播

通常我们需要在局域网来进行广播来查找主机,广播的意思就是向同网段的全部主机发送数据包。而在广域网是不允许的,可以想象广域网主机数量之多,广播造成网络堵塞。广播只能是udp,是由路由器向所有主机发送数据包,包括发送者本身。如果发送的是本身,可以留意下你收的IP:192.168.56.1。还有个组播的,这个在广域网和局域网都允许。

示例代码

服务器:

#include <boost/asio.hpp>
#include <boost/array.hpp>
#include <boost/bind.hpp>
#include <thread>
void handle_send()
{

};
int main()
{
  namespace ip = boost::asio::ip;
  boost::asio::io_service io_service;

  // Server binds to any address and any port.
  ip::udp::socket socket(io_service,
                         ip::udp::endpoint(ip::udp::v4(), 0));
  socket.set_option(boost::asio::socket_base::broadcast(true));

  // Broadcast will go to port 8888.
  ip::udp::endpoint broadcast_endpoint(ip::address_v4::broadcast(), 8888);

  // Broadcast data.
  boost::array<char, 4> buffer;
 // socket.send_to(boost::asio::buffer(buffer), broadcast_endpoint);
  socket.async_send_to(boost::asio::buffer(buffer), broadcast_endpoint,
	  boost::bind(&handle_send));
  io_service.run();
  //std::thread run_thread([&]{ io_service.run(); });
  //run_thread.join();
}

客户端:

#include <iostream>

#include <boost/asio.hpp>
#include <boost/array.hpp>
int main()
{
  namespace ip = boost::asio::ip;
  boost::asio::io_service io_service;

  // Client binds to any address on port 8888 (the same port on which
  // broadcast data is sent from server).
  ip::udp::socket socket(io_service,
                         ip::udp::endpoint(ip::udp::v4(), 8888 ));

  ip::udp::endpoint sender_endpoint;

  // Receive data.
  boost::array<char, 4> buffer;
  std::size_t bytes_transferred =
    socket.receive_from(boost::asio::buffer(buffer), sender_endpoint);

  std::cout << "remote host ip : " << sender_endpoint.address().to_string() << std::endl;
 // std::cout << "got " << bytes_transferred << " bytes." << std::endl;
}

总结

上面的例子是阻塞模式的广播,有兴趣的可以把它修改成异步模式的,记得udp不是可靠的,上面的例子出处来自国外忘记,,。。。