Boost asio--tcp server---1(无封装阻塞)

来源:互联网 发布:淘宝店铺一键装修 编辑:程序博客网 时间:2024/04/27 01:57

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

//这只一个阻塞模式的TCP服务器端程序
#include "stdafx.h"
#include <iostream>
#include <boost/asio.hpp>
using namespace boost::asio;
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
 int port = 60000;
 io_service io;

 boost::asio::ip::tcp::acceptor acceptor(io);//创建accept对象
 boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::tcp::v4(), port);//创建端点(IP和端口)
 acceptor.open(endpoint.protocol());
 //acceptor.set_option(boost::asio::ip::tcp::acceptor::reuse_address(false));//端口是否复用
 acceptor.bind(endpoint);//绑定端点
 acceptor.listen();//监听客户端连接
 char buff[1024]; 
 try
 {//
  while(1)
  {
   memset(buff,0,sizeof(buff)); //清空缓冲区
   ip::tcp::socket socket(io);  //定义一个socket 对象
   acceptor.accept(socket);  // 等待客户端链接过来,阻塞函数,客户端连接进来socket用于服务器和客户端的通信
   cout<<"客户端的Socket信息为:"<<socket.remote_endpoint().address()
    <<":"
    <<socket.remote_endpoint().port()
    <<std::endl;// 显示连接进来的客户端
   int size = socket.read_some(buffer(buff, 1024));// 接收客户端发送来的信息,阻塞函数
   buff[size] = '\0';
   std::cout<<"receive "<<size<<" bytes from client:\n"<<buff<<std::endl;  
   socket.write_some(buffer("hi, i am server!"));//服务器向客户端发送msg
   //buffer函数用于包装多种容器的缓冲区类型
  }
 }
 catch(exception &e)
 {
  cout<<e.what()<<endl;
 }
 return 0;
}