C++11 如何制作非阻塞服务器
我希望有一个非阻塞服务器来读取应用程序中的传入数据 这就是我想要的工作流程C++11 如何制作非阻塞服务器,c++11,boost,boost-asio,asyncsocket,C++11,Boost,Boost Asio,Asyncsocket,我希望有一个非阻塞服务器来读取应用程序中的传入数据 这就是我想要的工作流程 void main() { // create a socket server CreateSocket(); while( true ) { // keep doing the other tasks. // if we receive a message than process it } } 这是套接字连接的代码 #pragma once //importi
void main()
{
// create a socket server
CreateSocket();
while( true )
{
// keep doing the other tasks.
// if we receive a message than process it
}
}
这是套接字连接的代码
#pragma once
//importing libraries
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/enable_shared_from_this.hpp>
using namespace boost::asio;
using ip::tcp;
using std::cout;
using std::endl;
class con_handler : public boost::enable_shared_from_this<con_handler>
{
private:
tcp::socket sock;
std::string message = "Hello From Server";
enum { max_length = 2048};
char data[max_length];
public:
typedef boost::shared_ptr<con_handler> pointer;
con_handler(boost::asio::io_service& io_service) : sock( io_service) {}
// creating the pointer
static pointer create(boost::asio::io_service& io_service)
{
return pointer(new con_handler(io_service));
}
// socket creation
tcp::socket& socket()
{
return sock;
}
void start()
{
sock.async_read_some(
boost::asio::buffer(data, max_length),
boost::bind(&con_handler::handle_read,
shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
void handle_read(const boost::system::error_code& err, size_t bytes_transferred)
{
if (!err) {
cout << data << endl;
}
else {
std::cerr << "error: " << err.message() << std::endl;
sock.close();
}
}
void handle_write(const boost::system::error_code& err, size_t bytes_transferred)
{
if (!err) {
cout << "Server sent Hello message!" << endl;
}
else {
std::cerr << "error: " << err.message() << endl;
sock.close();
}
}
};
当前套接字连接正在工作,但它正在阻止另一个进程
我是否需要为此工作流使用单独的线程,或者我可以在同一个线程中执行此操作
这是我的主要功能
#include "pch.h"
#include <iostream>
#include "Server.h"
int main()
{
boost::asio::io_service io_service;
Server server(io_service);
io_service.run();
while (true)
{
std::cout << " function is running Running";
}
}
#包括“pch.h”
#包括
#包括“Server.h”
int main()
{
boost::asio::io_服务io_服务;
服务器(io_服务);
io_service.run();
while(true)
{
std::cout“阻止”的是什么?什么是“其他进程”?你能详细说明正在发生的事情和应该发生的事情吗?请尝试创建一个合适的演示,包括你实际的main
函数和你如何使用Server
类。@一些程序员朋友,我已经添加了main函数,请看一看。我想你需要这样做,它是做什么的。把它放在一个thr中ead是一个可能的解决方案。您的可能副本正在正确的道路上,您只需要。什么是“阻止”?什么是“其他进程”?你能详细说明正在发生的事情和应该发生的事情吗?请尝试创建一个合适的演示,包括你实际的main
函数和你如何使用Server
类。@一些程序员朋友,我已经添加了main函数,请看一看。我想你需要这样做,它是做什么的。把它放在一个thr中ead是一个可能的解决方案。你可能的副本在正确的道路上,你只需要。
#include "pch.h"
#include <iostream>
#include "Server.h"
int main()
{
boost::asio::io_service io_service;
Server server(io_service);
io_service.run();
while (true)
{
std::cout << " function is running Running";
}
}