客户端和服务端连接----同步连接

1. 使用boost库进行客户端连接步骤

flowchart TD A(启动客户端client) --> B[创建io_context] B --> C[创建 socket] C --> D[创建 endpoint] D --> E[调用 connect]

代码展示

#include <boost/asio.hpp>
#include <iostream>

namespace asio = boost::asio;
using tcp = asio::ip::tcp;

int connect_to_server(const std::string& serverIp, unsigned short port)
{
	try
	{
		asio::io_context ioc; //创建ioc上下文
		tcp::socket sock(ioc); // 创建socket对象
		auto server_address = asio::ip::make_address(serverIp); 
		tcp::endpoint endpoint = tcp::endpoint(server_address, port); // 构造服务端endpoint
		boost::system::error_code ec; //监听错误
		sock.connect(endpoint,ec); //连接服务端
		if (ec)
		{
			std::cout << ec.message() << std::endl;
			return -1;
		}
		return 0;

	}
	catch (const std::exception& err)
	{
		// 捕获make_address可能会产生的异常
		std::cout << err.what() << std::endl;
		return -1;
	}
}

2.使用boost进行服务端监听步骤

flowchart TD A(启动服务端server) --> B[创建io_context] B --> C[创建 acceptor] C --> D[进行 open] D --> E[进行 bind] E --> F[调用 listen 监听本地端口] F --> G[调用accept 接收客户端连接]
int acceptClient1()
{
	try
	{
		asio::io_context ioc; //创建上下文对象
		tcp::acceptor acceptor(ioc); //创建服务端socket
		acceptor.open(tcp::v4()); //open
		tcp::endpoint endpoint(asio::ip::address_v4::any(), 6666); 
		boost::system::error_code ec;
		acceptor.bind(endpoint, ec); //bind
		if (ec)
		{
			std::cout << "bind error: " << ec.message();
			return -1;
		}
		acceptor.listen(32, ec);
		if (ec)
		{
			std::cout << "listen error: " << ec.message();
			return -1;
		}
		tcp::socket clientSock = acceptor.accept();
		return 0;
	}
	catch (const std::exception& error)
	{
		std::cout << error.what() << std::endl;
		return -1;
	}

}
int acceptClient2()
{
	try
	{
		asio::io_context ioc; //创建上下文对象
		tcp::endpoint endpoint(asio::ip::address_v4::any(), 6666);
		tcp::acceptor acceptor(ioc, endpoint); //实现 open + bind + listen
		tcp::socket clientSock = acceptor.accept();
		return 0;
	}
	catch(const std::exception& error)
	{
		std::cout << error.what() << std::endl;
		return -1;
	}
}

posted on 2025-11-30 20:20  珂k  阅读(6)  评论(0)    收藏  举报