boost 1.57 asio socket重复使用

去年用boost::asio::ip::tcp::socke(大概是boost 1.4.x版本)t时,服务器需要复用socket,socket关闭后,不能再accept,今天无聊中简单测试下,在1.5.7中似乎没问题。代码如下:

// TestC11.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include 
#include 
#include 
typedef std::shared_ptr socket_ptr;

void clientSession(socket_ptr socket)
{
	while (true)
	{
		char buf[256];
		boost::system::error_code ec;
		size_t len;
			
		len = socket->read_some(boost::asio::buffer(buf), ec);

		write(*socket, boost::asio::buffer(buf, len));
		buf[len] = 0;
		std::cout << buf;
	}
}

int main(int argc, char **argv)
{
	boost::asio::io_service ios;
	boost::asio::ip::tcp::endpoint ep(boost::asio::ip::tcp::v4(), 2002);
	boost::asio::ip::tcp::acceptor acc(ios, ep);

	socket_ptr socket(new boost::asio::ip::tcp::socket(ios));
	while (1)
	{
		acc.accept(*socket);
		//std::thread t(&clientSession, socket);
		//t.detach();

		// modify for test socket reuse.
		char buf[256];
		boost::system::error_code ec;
		size_t len;

		len = socket->read_some(boost::asio::buffer(buf), ec);

		write(*socket, boost::asio::buffer(buf, len));
		buf[len] = 0;
		std::cout << buf;
		socket->close();

		//socket->open(boost::asio::ip::tcp::v4());
	}
}
用telnet 127.0.0.1 2002测试,没有问题。连接后发送一个字符,主机就强迫关闭,然后重新连接,重复以上过程没有问题。爽!重新写个简单的tcp/ip服务器。

你可能感兴趣的:(BOOST)