Multi-threaded game server Development (2)-Writing network libraries

Source: Internet
Author: User
Tags lock queue set time

Network Library function Introductionfeatures of the network library

1 Multi- threading

2. listening on a port

3. connecting to a remote server

4. Save and manage all links, external and network library operations via link ID

5. sending data to a connection

6. Force a link to close

7. Network Event Fallback: Connect, receive, close

8. Error Handling


Network Library main interface (file: tcp_frame.h)
Class tcp_frame{public:/*** Tcp_frame constructor * @handler Network event back (Connect, Recevie, close) * @net_thread_num number of network threads * Note: If more than one network thread is turned on, the handler rollback function is non-thread safe. See *broker::on_net_message, which uses the lock queue */tcp_frame (const net_message_hander& handler, uint8_t net_thread_num = 1); Tcp_frame ();/*** listens on a port * @listenAddress IP address or domain name * @listenPort Port */voidlisten (const std::string& IP, const std:: string& Port, module_id moduleid);/*** Connect a port * @ip IP address or domain name * @port Port * @moduleid module identifier, in general the network library is a reference to a module as part of the real Is. * Network events are inserted into the message queue of the module as messages (message). */voidconnect (const std::string& IP, const std::string& port, module_id ModuleID)/*** send data to a link * @sockid connection identification * @data data */voidsend (socket_id sockid, const buffer_ptr& data);/*** close a link * @so Ckid Connection Identification * @state set a status for the link indicating why it was closed (such as timeout, sending illegal data) */voidclose_socket (socket_id sockid, esocketstate State);/*** Start Network library */ Voidrun ();/*** Stop Network Library */voidstop ();/*** get error code */intgeterrorcode ();/*** get error message */std::stringgeterrormessage ();/*** Set time-out detection for management links * @timeout time-out, unit ms*@checkInterval time-out detection interval, unit ms*/voidsettimeout (uint32_t timeout, uint32_t checkinterval);p rotected:/*** post Asynchronous Accept, Accept network connection */voidpostaccept ();/*** timeout detection thread function */voidchecktimeout (uint32_t interval);p rotected:struct imp;std::shared_ptr <Imp> _imp;net_message_hander _hander;};

The network library uses example 1. Echoserver Server Code:
#pragma once#include <common/noncopyable.hpp> #include <tcp_frame.h> #include <message.h> #include <buffer_reader.h> #include <string> #include <iostream> #include <functional>using namespace Moon;class Echoserver:noncopyable{public:echoserver () {}~echoserver () {if (m_net! = nullptr) {//Shut down network thread m_net->stop ( );}} void Start () {Auto Handler = Std::bind (&echoserver::onnetmessage, this, std::p laceholders::_1); m_net = Std::make_ Shared<tcp_frame> (handler,2);//2 network thread//listen to the local 11111 port, because this is only with the network library, do not care about the module, module ID 0 can be m_net->listen ("127.0.0.1 "," 11111 ", Module_id::create (0));//Start Network thread M_net->run ();//The main thread should normally be blocked to prevent the main thread from exiting. The main thread}private:void onnetmessage (const message& msg) {switch (Msg.get_type ()) {case Emessagetype is no longer blocked because the client will run within the main thread later :: socketconnect:{//connection, message content defaults to remote host address Buffer_reader BR (Msg.data (), msg.size ()); std::string addr;br >> addr;std:: cout << "Server:client connect" <<addr<< std::endl;break;} Case emessagetype::socketdata:{//received data, the message holds the sender and receiver's id.//if it is a network message, then the sender obtains the network connection for the network connection id//Idauto Sockid = msg.get_socket_id (); Buffer_reader BR (Msg.data ( ), Msg.size ());//Get the information sent std::string clientmsg;br >> clientmsg;//send the message back (Echomsg is smart pointer, convenient multi-threading memory management) Auto Echomsg = Buffer::create (Clientmsg.size () + 1);(*echomsg) << clientmsg;m_net->send (Sockid, echomsg); Std::cout < < "Server:echo msg" << clientmsg << Std::endl;break;} Case emessagetype::socketclose:{//Disconnect Buffer_reader br (Msg.data (), msg.size ()); std::string addr;br >> addr;std:: cout << "server:client close" << addr << std::endl;break;} Default:break;}} Private:std::shared_ptr<tcp_frame> m_net;};


Client code:
#pragma once#include <common/noncopyable.hpp> #include <tcp_frame.h> #include <message.h> #include <buffer_reader.h> #include <string> #include <iostream> #include <functional>using namespace Moon;class echoclient{public:void Start () {Auto Handler = Std::bind (&echoclient::onnetmessage, this, std:: placeholders::_1); m_net = Std::make_shared<tcp_frame> (handler, 1);//1 Network threads//connection to the 11111 port of the machine, because this is only using the network library, do not care about the module, Module ID 0 is Auto id = m_net->sync_connect ("127.0.0.1", "11111", Module_id::create (0)); if (Id.value = = 0) {std::cout <& Lt "Client:connect Server failed" << Std::endl;return;} Start Network thread M_net->run (); std::string str;std::cin >> str;while (str! = "Exit") {std::cout << client:send msg "<<str<< std::endl;auto msg = buffer::create (str.size () + 1);(*msg) << str;m_net->send (ID, msg); Std::cin >> str;} M_net->stop ();} Private:void onnetmessage (const message& msg) {switch (Msg.get_type ()) {case EmessagEtype::socketconnect:{buffer_reader BR (Msg.data (), Msg.size ()) std::string addr;br >> addr;std::cout << " Client:connect server: "<< addr << std::endl;break;} Case emessagetype::socketdata:{//Get network connection Idauto Sockid = msg.get_socket_id (); Buffer_reader br (Msg.data (), Msg.size ()) ;//Get information sent std::string clientmsg;br >> clientmsg;std::cout << "client:recv msg" << clientmsg << S Td::endl;break;break;} Case emessagetype::socketclose:{//disconnects, message content defaults to client address Buffer_reader BR (Msg.data (), msg.size ()); std::string addr;br > > Addr;std::cout << "client:server close" << addr << std::endl;break;} Default:break;}} Private:std::shared_ptr<tcp_frame> m_net;};




Using the example

#include "echoclient.hpp" #include "echoserver.hpp" int main () {Echoserver svr;svr. Start (); Echoclient CL;CL. Start ();    return 0;}



Example address: Click the Open link



Multi-threaded game server Development (2)-Writing network libraries

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.