【cocos2dx网络游戏】搭建CS架构的基本通信框架(一)Client

来源:互联网 发布:eplan软件大小 编辑:程序博客网 时间:2024/06/14 01:52
新建空白win32项目MClient
新建main.cpp 
#include <iostream>using namespace std;#include "comm.h"void proc_data(socket_type sock){//输出客户端的地址的字符串cout<<"client connected :"<<sock->remote_endpoint().address()<<endl;while (true){//捕获可能发生的异常try{//使用字符数组vector<char> str(100, 0);//读取客户端发送的数据//同步机制,阻塞读取数据sock->read_some(buffer(str));cout<<"recv from:"<<sock->remote_endpoint().address()<<endl;cout<<"data:"<<&str[0]<<endl;cout<<endl;//将客户端发送的数据回显sock->write_some(buffer(str));}catch(std::exception& e){cout<<e.what()<<endl;break;}}}//处理网络连接void proc_accept(){cout<<"wait connect..."<<endl;io_service ios;  //asio程序必须的io_service对象ip::tcp::endpoint ep(ip::tcp::v4(), PORT_NUM);//用于接收连接ip::tcp::acceptor acceptor(ios, ep);while (true){//初始化一个socket对象socket_type sock(new ip::tcp::socket(ios));//阻塞等待socket连接acceptor.accept(*sock);//为每一个建立连接的客户端建立一个线程处理数据thread t(proc_data, sock);}}int main(int argc, char *argv[]){//创建线程,以及传递线程处理函数thread t1(proc_accept);//线程阻塞等待,知道线程处理结束t1.join();return 0;};
使用之前服务端用的comm.h
#ifndef _COMM_H#define _COMM_H#include <boost/asio.hpp>#include <boost/shared_ptr.hpp>#include <boost/make_shared.hpp>#include <boost/bind.hpp>#include <boost/function.hpp>#include <boost/thread.hpp>#include <boost/asio/placeholders.hpp>#include <boost/date_time/posix_time/posix_time.hpp>using namespace boost::asio;using namespace boost;#include <string>#include <vector>#include <iostream>using namespace std;#define PORT_NUM  9999 //端口号typedef  boost::shared_ptr<ip::tcp::socket> socket_type;#endif



0 0