您当前的位置: 首页 > 

phymat.nico

暂无认证

  • 3浏览

    0关注

    1967博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

boost之asio同步io使用实例

phymat.nico 发布时间:2017-10-08 15:17:05 ,浏览量:3

// boost_sync_client.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"

#include 
#include 
#include 
#include 
#include 
#include 
#include 

#include 
#include 
#include 
#include 
#include 
#include 

#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "mswsock.lib")

using namespace boost::asio;
int tcp_sync_client(const char *ip,unsigned short port)
{
	boost::asio::io_service service;
	boost::asio::ip::tcp::endpoint ep(boost::asio::ip::address::from_string(ip), port);
	boost::asio::ip::tcp::socket sock(service);
	try
	{
		sock.connect(ep);
	}
	catch (const boost::system::system_error& e)
	{
		return e.code().value();
	}

	int ret = sock.send(boost::asio::buffer("hello i am client"));
	if (ret < 0)
	{
		return ret;
	}
	while (1)
	{
		char data[512];
		int len = sock.read_some(boost::asio::buffer(data));
		if (len > 0)
		{
			printf("recv data:%s\n",data);
			/*int ret = sock.send(boost::asio::buffer("hello i am client"));
			if (ret < 0)
			{
				printf("send failed:%d\n",ret);
				return ret;
			}*/
		}
	}
	return 0;
}


int _tmain(int argc, _TCHAR* argv[])
{
	tcp_sync_client("0.0.0.0", 5000);
	return 0;
}

// boost_sync_server.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#include 
#include 
#include 
#include 
#include 
#include 

#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "mswsock.lib")
using namespace boost::asio;
void client_session(sock_ptr sock)
{
	while (1)
	{
		char data[512];
		size_t len = sock->read_some(boost::asio::buffer(data,512));
		if (len > 0)
		{
			write(*sock,boost::asio::buffer("ok",2));
			sock->write_some(boost::asio::buffer("ok",2));
		}
	}
}

void tcp_sync_sever()
{
	boost::asio::io_service service;
	boost::asio::ip::tcp::endpoint ep(ip::tcp::v4(), 5000);
	boost::asio::ip::tcp::acceptor acc(service, ep);
	while (1)
	{
		sock_ptr sock(new ip::tcp::socket(service));
		acc.accept(*sock);
		boost::thread(boost::bind(client_session, sock));
	}
}
int _tmain(int argc, _TCHAR* argv[])
{
	tcp_sync_sever();
	return 0;
}

关注
打赏
1659628745
查看更多评论
立即登录/注册

微信扫码登录

0.0446s