UDP简单并发服务器

用Boost.Asio库实现的UDP并发服务器。(简单记录,作为备忘)

线程池参考:https://blog.csdn.net/liushengxi_root/article/details/83932654

服务端:

//Server.h
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <string>
#include "threadpool.h"

typedef boost::shared_ptr<boost::asio::ip::udp::socket> socket_ptr;
typedef boost::asio::ip::udp::endpoint endpoint;

class Server
{
public:
    Server();

    void acceptMessage();     //接收客户端消息
    void processMessage(std::string message, endpoint ep);  //处理消息

private:
    ThreadPool threadpool;  //线程池
};

//Server.cpp
#include "server.h"
#include <iostream>

typedef boost::shared_ptr<boost::asio::ip::udp::socket> udpsocket_ptr;   //处理请求消息
typedef boost::shared_ptr<boost::asio::ip::tcp::socket> tcpsocket_ptr;   //传输文件
typedef boost::asio::ip::udp::endpoint endpoint;    //客户端端口号

boost::asio::io_service service;
boost::asio::ip::udp::endpoint udpep(boost::asio::ip::udp::v4(),8001);
boost::asio::ip::udp::socket udpsock(service,udpep);

Server::Server()
{

}

void Server::acceptMessage()
{
    while (1) {

        char datarec[512];
        memset(datarec,0,sizeof (char) * 512);

        boost::asio::ip::udp::endpoint sender_ep;

        int bytes = udpsock.receive_from(boost::asio::buffer(datarec),sender_ep);

        std::string s = datarec;

        threadpool.append(std::bind(&Server::processMessage, this,s,sender_ep));
    }
}

void Server::processMessage(std::string message,endpoint ep)
{
    std::cout << ep.address().to_string() + " send: " + message << std::endl;
    udpsocket_ptr sock(new boost::asio::ip::udp::socket(service,boost::asio::ip::udp::endpoint()));
    std::string s = "message";
    sock->send_to(boost::asio::buffer(s),ep);

}

客户端:

向客户端发送请求并接收回复消息。


void Client::sendMessage()
{
    char s[512];
    strcpy(s,"aaa");
    char data[512];

    try {
        sock.send_to(boost::asio::buffer(s),ep);
         boost::asio::ip::udp::endpoint sender_ep;
        sock.receive_from(boost::asio::buffer(data),sender_ep);
        std::string s = data;
        qDebug() << sender_ep.address().to_string().data() << " send: " << s.data();

    } catch (boost::system::system_error e) {
        std::cerr << e.what() << std::endl;
    }

}

猜你喜欢

转载自blog.csdn.net/weixin_42439026/article/details/89286170