您的位置:首页 > 理论基础 > 计算机网络

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

2014-12-19 00:12 615 查看
前面server中我们已经在share中创建了msg_def.h tcp_message.h tcp_message.cpp test_tcp_message.h 四个文件,在Client同样引入

在客户端中我们主要也还是修改消息的发送,修改Client中的main.cpp

#include <iostream>
using namespace std;
#include "comm.h"

#include "test_tcp_message.h"

void proc_connect(socket_type sock, ip::tcp::endpoint& ep)
{
bool bConnectFlag = false;
while (true)
{
//当没有连接上服务器时,每隔一秒连接一次
try
{
if (!bConnectFlag)
{
cout<<"connecting..."<<endl;

//阻塞的timer
io_service ios;
deadline_timer timer(ios, posix_time::seconds(1));
timer.wait();  //进行同步等待
sock->connect(ep);
}
else
{
//向服务器发送数据
cout<<endl<<"please input:";
string str;
cin>>str;

//////////////////////////////////////////////////////////////////////////
//test tcp_message 使用tcp_message进行数据的包装
cout<<"///////////////////////////////////////////"<<endl;
cout<<"send data to server..."<<endl;
send_data(sock, str);
cout<<endl;
cout<<"recv data from server..."<<endl;
read_data(sock);
cout<<"///////////////////////////////////////////"<<endl<<endl;
}
bConnectFlag = true;
}
//捕获网络异常
catch(std::exception& e)
{
sock->close();
bConnectFlag = false;
cout<<e.what()<<endl;
}
}
}

int main(int argc, int argv[])
{
//初始化ios对象
io_service ios;

//初始化连接服务器的socket
socket_type sock(new ip::tcp::socket(ios));

//初始化需要连接的服务器的地址以及端口号
ip::tcp::endpoint ep(ip::address::from_string("127.0.0.1"), PORT_NUM);
thread t1(proc_connect, sock, ep);
t1.join();
return 0;
}
我们来看下效果,在客户端中输入 ssss

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