CN109308202A - A kind of method and mobile terminal linking barrage - Google Patents

A kind of method and mobile terminal linking barrage Download PDF

Info

Publication number
CN109308202A
CN109308202A CN201811067826.4A CN201811067826A CN109308202A CN 109308202 A CN109308202 A CN 109308202A CN 201811067826 A CN201811067826 A CN 201811067826A CN 109308202 A CN109308202 A CN 109308202A
Authority
CN
China
Prior art keywords
message
subscriber
class
interface
function
Prior art date
Legal status (The legal status is an assumption and is not a legal conclusion. Google has not performed a legal analysis and makes no representation as to the accuracy of the status listed.)
Pending
Application number
CN201811067826.4A
Other languages
Chinese (zh)
Inventor
周志刚
Current Assignee (The listed assignees may be inaccurate. Google has not performed a legal analysis and makes no representation or warranty as to the accuracy of the list.)
Wuhan Douyu Network Technology Co Ltd
Original Assignee
Wuhan Douyu Network Technology Co Ltd
Priority date (The priority date is an assumption and is not a legal conclusion. Google has not performed a legal analysis and makes no representation as to the accuracy of the date listed.)
Filing date
Publication date
Application filed by Wuhan Douyu Network Technology Co Ltd filed Critical Wuhan Douyu Network Technology Co Ltd
Priority to CN201811067826.4A priority Critical patent/CN109308202A/en
Publication of CN109308202A publication Critical patent/CN109308202A/en
Pending legal-status Critical Current

Links

Classifications

    • GPHYSICS
    • G06COMPUTING; CALCULATING OR COUNTING
    • G06FELECTRIC DIGITAL DATA PROCESSING
    • G06F9/00Arrangements for program control, e.g. control units
    • G06F9/06Arrangements for program control, e.g. control units using stored programs, i.e. using an internal store of processing equipment to receive or retain programs
    • G06F9/44Arrangements for executing specific programs
    • G06F9/448Execution paradigms, e.g. implementations of programming paradigms
    • G06F9/4488Object-oriented
    • HELECTRICITY
    • H04ELECTRIC COMMUNICATION TECHNIQUE
    • H04NPICTORIAL COMMUNICATION, e.g. TELEVISION
    • H04N21/00Selective content distribution, e.g. interactive television or video on demand [VOD]
    • H04N21/40Client devices specifically adapted for the reception of or interaction with content, e.g. set-top-box [STB]; Operations thereof
    • H04N21/43Processing of content or additional data, e.g. demultiplexing additional data from a digital video stream; Elementary client operations, e.g. monitoring of home network or synchronising decoder's clock; Client middleware
    • H04N21/435Processing of additional data, e.g. decrypting of additional data, reconstructing software from modules extracted from the transport stream
    • HELECTRICITY
    • H04ELECTRIC COMMUNICATION TECHNIQUE
    • H04NPICTORIAL COMMUNICATION, e.g. TELEVISION
    • H04N21/00Selective content distribution, e.g. interactive television or video on demand [VOD]
    • H04N21/40Client devices specifically adapted for the reception of or interaction with content, e.g. set-top-box [STB]; Operations thereof
    • H04N21/47End-user applications
    • H04N21/488Data services, e.g. news ticker
    • H04N21/4884Data services, e.g. news ticker for displaying subtitles

Landscapes

  • Engineering & Computer Science (AREA)
  • Software Systems (AREA)
  • Theoretical Computer Science (AREA)
  • Multimedia (AREA)
  • Signal Processing (AREA)
  • Physics & Mathematics (AREA)
  • General Engineering & Computer Science (AREA)
  • General Physics & Mathematics (AREA)
  • Mobile Radio Communication Systems (AREA)

Abstract

The invention discloses a kind of methods and mobile terminal for linking barrage, are optimized for the process to link barrage, improve the efficiency of link barrage.The method of the present invention comprises determining that message subscribing person's abstraction interface based on C Plus Plus;Determine the abstraction interface prevents object copies function;It generates message subscribing person and manages class, the subscriber manages class for being managed to subscriber;It carries out subscribing to interested message to interface offer subscriber is write by the interface of subscriber management class;Class is managed to the message subscribing person and carries out message parsing and by the message distribution being resolved to all subscribers;Determine the subscriber of each message.

Description

A kind of method and mobile terminal linking barrage
Technical field
The present invention relates to field of terminal more particularly to a kind of methods and mobile terminal for linking barrage.
Background technique
With the fast development of Internet technology, the function of mobile terminal is more and more abundant, for promoting user experience Barrage function also appears on mobile terminal.
It is all usually by the barrage scheme of personal computer (personal computer, PC) client in traditional scheme It is transplanted in mobile terminal.And have its characteristic, such as unstable networks for mobile terminal, mobile 4G network is used, And mobile terminal meeting process is mobile, for example, mobile terminal is moved to the bad place of network signal;Alternatively, being cut from 3G network Change to 4G network;Alternatively, (wireless fidelity, the WIFI) network from 4G network switching to Wireless Fidelity;Alternatively, from WIFI is switched to 4G network etc..Simultaneously for barrage link also due to client a variety of causes or due to the original of account Cause, in link, server judges client validity, so that error code etc. can be returned, therefore client is also required to consider clothes The error code of business device.
The barrage of the traditional scheme of client connection server in to(for) mobile terminal connects, and only considered the available of function Property, there is no the characteristics for considering mobile terminal, for example, unstable networks, mobile terminal electric quantity consumption, the characteristics such as fever.Cause This, the connection between mobile terminal and barrage server is easy to interrupt, and the process for restoring connection is slow.
Summary of the invention
The embodiment of the invention provides it is a kind of link barrage method and mobile terminal, for link barrage process into It has gone optimization, has improved the treatment effeciency of link barrage.
The first aspect of the embodiment of the present invention provides a kind of method for linking barrage, comprising: determines based on C Plus Plus Message subscribing person's abstraction interface;Determine the abstraction interface prevents object copies function;It generates message subscribing person and manages class, institute It states subscriber and manages class for being managed to subscriber;It is ordered by the interface that the subscriber manages class to interface offer is write Reader carries out subscribing to interested message;The message that class carries out message parsing and will be resolved to is managed to the message subscribing person It is distributed to all subscribers;Determine the subscriber of each message.
In a kind of possible embodiment, message subscribing person abstraction interface of the determination based on C Plus Plus includes: definition Abstraction interface class MessageObserver, the class MessageObserver of message subscribing person;Define the abstraction interface Destructor function virtual~MessageObserver () of class;Define abstraction interface GetObserverMessageType;It is fixed Adopted abstraction interface OnRecvPackMsg.
In a kind of possible embodiment, the object copies function that prevents of the determination abstraction interface includes: that will copy Shellfish constructed fuction is defined as the existing function private:void operator=(const MessageObserver&) of empty real; The copy-constructor function is defined as the existing function MessageObserver (const of privately owned empty real MessageObserver&)。
In a kind of possible embodiment, the generation message subscribing person manages class, the subscriber manage class for pair It includes: to define a message management person class class ObserverManager that subscriber, which is managed,;Generate std:: Multimap<std::string, MessageObserver*>map_push_observer, and pass through multimap pairs of function The subscriber of message is managed;The object map_push_observer of the function multimap is generated to store described order Reader.
In a kind of possible embodiment, it is described by the subscriber manage class ObserverManager interface to It writes interface and provides subscriber subscribe to interested message include: by interface void SetMessageTypeObserver (MessageObserver*_taskObserver) is supplied to all subscriber's dealing message All subscribers registered in management object;Subscriber is obtained by abstraction interface GetObserverMessageType to need to order All type of messages read;Obtain return value _ cmdtypes, the return value store subscription in need type of message; Define an iterator objects std::set<std::string>:: iterator itr;Initialize iterator itr=_ cmdtypes.begin();For circulation is write to traverse to obtain each type of message;Call multimap container Insert interface is inserted into subscriber into container.
It is described that class progress message parsing is managed to the message subscribing person and will be resolved in a kind of possible embodiment Message distribution to all subscribers include: creation one message parser pDecoder;By message storage to mq.read In buf in (buf, len);The type type that the buf obtains message is parsed by calling the message parser;Creation One interface function is distributed the message to corresponding subscriber.
In a kind of possible embodiment, the creation one interface is distributed the message to corresponding subscription Person includes: subscriber's number n that the message is obtained by the count function of multimap container;Define an iterator std::multimap<std::string,MessageObserver*>::itrator itr;Find function is called to come from iteration Corresponding subscriber is searched in device;After finding by subscriber storage into iterator itr;It will be described by for circulation Message is distributed to each subscriber one by one.
The second aspect of the embodiment of the present invention provides a kind of mobile terminal, comprising: the first determination unit, for determining base In message subscribing person's abstraction interface of C Plus Plus;Second determination unit prevents object copies for determine the abstraction interface Function;Generation unit, for generating message subscribing, person manages class, and the subscriber manages class for being managed to subscriber; Subscriber units, the interface for managing class by the subscriber are interested subscribe to interface offer subscriber is write Message;Dispatching Unit is parsed, for managing the message distribution that class carries out message parsing and will be resolved to the message subscribing person To all subscribers;Third determination unit, for determining the subscriber of each message.
Third aspect present invention provides a kind of electronic equipment, including memory, processor, which is characterized in that the place It is realized as described in above-mentioned first aspect any one when reason device is for executing the computer management class method stored in memory The step of linking the method for barrage.
The fourth aspect of the application provides a kind of computer readable storage medium, in the computer readable storage medium It is stored with instruction, when run on a computer, so that computer executes method described in above-mentioned various aspects.
The 5th aspect of the application provides a kind of computer program product comprising instruction, when it runs on computers When, so that computer executes method described in above-mentioned various aspects.
Detailed description of the invention
Fig. 1 is a kind of flow chart of method for linking barrage provided in an embodiment of the present invention;
Fig. 2 is a kind of structural schematic diagram of mobile terminal provided in an embodiment of the present invention;
Fig. 3 is a kind of hardware structural diagram of possible electronic equipment provided in an embodiment of the present invention;
Fig. 4 is a kind of hardware structural diagram of possible computer readable storage medium provided in an embodiment of the present invention.
Specific embodiment
The embodiment of the invention provides it is a kind of link barrage method and mobile terminal, for link barrage process into It has gone optimization, has improved the efficiency of link barrage.
Following will be combined with the drawings in the embodiments of the present invention, and technical solution in the embodiment of the present invention carries out clear, complete Site preparation description, it is clear that described embodiments are only a part of the embodiments of the present invention, instead of all the embodiments.It is based on Embodiment in the present invention, those skilled in the art's every other implementation obtained without making creative work Example, shall fall within the protection scope of the present invention.
The description and claims of this application and term " first ", " second ", " third ", " in above-mentioned attached drawing The (if present)s such as four " are to be used to distinguish similar objects, without being used to describe a particular order or precedence order.It should manage The data that solution uses in this way are interchangeable under appropriate circumstances, so that the embodiments described herein can be in addition to illustrating herein Or the sequence other than the content of description is implemented.In addition, term " includes " and " having " and their any deformation, it is intended that Cover it is non-exclusive include, for example, containing the process, method, system, product or equipment of a series of steps or units need not limit In step or unit those of is clearly listed, but may include be not clearly listed or for these process, methods, produce The other step or units of product or equipment inherently.
Embodiment one
Referring to Fig. 1, a kind of flow chart of method for linking barrage provided in an embodiment of the present invention, comprising:
101, message subscribing person's abstraction interface based on C Plus Plus is determined.
The present embodiment is the design that a kind of interface is developed based on C Plus Plus, designs a kind of unification to message subscriber Interface and abstract class, message subscribing person must then realize the total interface of abstract class, and message management class needs disappear to all Breath subscriber is managed.Firstly the need of abstraction interface the class MessageObserver, class for defining message subscribing person MessageObserver
{ define open function: public:MessageObserver () { } does not need to realize that function is sky function Energy;
Its destructor function is defined, and it is empty destructor function that virtual must be added, which to indicate, because it is bottom base class, RAM leakage must be defined as Virtual Function, virtual~MessageObserver () { } in order to prevent;Define abstraction interface letter Number GetObserverMessageType indicates to obtain all type of messages of Subscriber subscriptions, and joined=0 in code Expression is an abstraction interface;
Wherein return type is the set container of stl container, and wherein type of message is all a string type, virtual Const std::set < std::string>&GetObserverMessageType ()=0;std::set<std::string > indicate to can store multiple and different type of messages, and type of message cannot be identical.Then another abstraction interface is defined OnRecvPackMsg indicates that bottom-layer network receives network data transmitting to subscriber.
This function also must be Virtual Function, and=0 expression must be added to be abstraction interface, wherein parameter const std:: String&_cmdtype indicates the type of message currently pushed, and wherein parameter const char*pservermessage is indicated whole A message content, virtual void OnRecvPackMsg (const std::string&_cmdtype, const char* Pservermessage)=0.
102, determine abstraction interface prevents object copies function.
Next since this subscriber's the present embodiment does not allow it to carry out the copy between object, so needing that structure will be copied Function is made to be defined as the existing function of empty real and need to be put into private function.Assignment copy function is defined as privately owned empty real Existing function, private:void operator=(const MessageObserver&);Copy-constructor function is defined as The existing function of privately owned empty real, MessageObserver (const MessageObserver&);So far, the interface of subscriber Its all definition is completed in class.Subsequent all specific subscribers are based on abstract class MessageObserver then to define certainly Oneself realization.
103, it generates message subscribing person and manages class, subscriber manages class for being managed to subscriber.
A message management person class class ObserverManager is defined first;The present embodiment is based on type of message Subscriber is designed, each subscriber can subscribe to oneself interested type of message, while a type of message may also There are multiple subscribers.So it needs member variable to store all message subscribing persons, while the message subscribing person having can order Read multiple type of messages.The present embodiment is managed message subscriber using the multimap container of STL, why uses Multimap be because each message subscribing person may subscribe to multiple message, simultaneously because message is very frequent, so It is also required to quickly find all subscribers of message, so the present embodiment manages message subscribing using multimap Person and query messages subscriber.The object map_push_observer of a multimap is created to store subscriber, wherein The key value of multimap is the type that std::string indicates message, and the vlaue value of multimap is MessageObserver Indicate the pointer to object of subscriber, std::multimap<std::string, MessageObserver*>map_push_ observer。
104, the interface that class is managed by subscriber carries out subscribing to interested message to interface offer subscriber is write.
This interface is supplied to all subscribers registered in all subscriber's dealing message management objects, it is necessary to be inherit in The subscriber write before the present embodiment is based on abstract class MessageObserver, void SetMessageTypeObserver(MessageObserver*_taskObserver){
It is following then need to obtain subscriber and need all type of messages for subscribing to.Since subscriber provides unified pumping It is obtained as interface GetObserverMessageType;
Const std::set<std::string>&_cmdtypes=_taskObserver->
Wherein return value _ cmdtypes then store subscription in need type of message, GetObserverMessageType();Next it needs to be traversed for this return value and obtains all type of messages;Define one Iterator objects std::set<std::string>:: iterator itr;Initialize iterator itr=_ cmdtypes.begin();Next for circulation is write to traverse to obtain each type of message, and the end of circulation then judges Whether iterator is equal to _ cmdtypes.end ();for(;itr!=_ cmdtypes.end ();Message is obtained from iterator Type is strType, ++ itr) { string strType=(* itr);Insert that is following then calling multimap container A subscriber is inserted into interface dealing container;map_push_observer.insert(std::pair<std::string, MessageObserver*>(strType,_taskObserver));Wherein strType then indicates the type of message subscribed to, TaskObserver then indicates subscriber.
}
So far this interface then complete the realization registered to subscriber.
105, class is managed to message subscriber and carries out message parsing and by message distribution to all subscribers.
In step 2, it after mobile terminal has received the network data of server, can all be stored in message queue mq.To team We require to carry out parsing message for each message in column, then managing message distribution class are called to be distributed message To corresponding subscriber.
Firstly the need of the resolver pDecoder, MessageDecoder*pDecoder=new of one message of creation MessageDecoder();Then a piece of news is read from queue to be parsed;
So message is then stored and has been arrived in buf, mq.read (buf, len);Then the resolver of message is called to disappear to parse Buf is ceased, the type type, pDecoder- > Parse (buf) of message are obtained from message parser;To obtain message Type is cmdtype, std::string cmdtype=pDecoder- > GetItem (" type ");It is following then need to offset Breath is distributed.The present embodiment writes an interface to be distributed message to corresponding subscriber;void DispatchMessage (char*pMessage, string cmdtype) { passes through the count function of multimap container first To obtain subscriber's number n, int n=map_push_observer.count (cmdtype) of the message;Pass through first The count function of multimap container obtains the subscriber number n of the message, then defines an iterator std:: multimap<std::string,MessageObserver*>::itrator itr;Then find function is called to come from iteration Corresponding subscriber is searched in device.
After finding next storage writes for circulation then into iterator itr to be distributed to each subscription one by one Person, itr=map_push_observer.find (cmdtype);
For (int i=0;i<n;i++){
Firstly the need of judging that subscriber whether there is;
if(it!=map_push_observer_.end () &&it- > second)
And then its corresponding message sink interface OnRecvPackMsg is called to each subscriber;
When message subscribing person has subscribed the message that type of message is cmdtype, then can be triggered OnRecvPackMsg, It can be by message distribution to subscriber;To which subscriber can be further processed message, it- > second- > OnRecvPackMsg(cmdtype,pMessage);For example, being present message subscribing person, then can show on a user interface The present message being currently received;It is barrage message subscribing person, then can shows the barrage message being currently received on a user interface Content.
}
++it;
}
So far complete message subscriber design, the management of subscriber subscribes to the distribution of message.
106, the subscriber of each message is determined.
The present embodiment determines the subscriber of each barrage message.
class DanmuMessageObserver:public MessageObserver{
It must realize all abstraction interface functions of MessageObserver, public;
const std::set<std::string>&GetObserverMessageType(){
A static container object types is defined first;
static std::set<std::string>types;
Judgement it is lower if types stored subscription in need message if directly return;Otherwise it is ordered without deposit The message read.
if(!types.empty()){
return types;
}
types.insert(danmu_TYPE);
By calling insert function that can then be inserted into a type of message into container object.The present embodiment is that barrage disappears Breath then subscribes to danmu_TYPE;
Realize another abstraction interface OnRecvPackMsg.
void OnRecvPackMsg(const std::string&_cmdtype,const char* pservermessage){
When message subscribing distribution management module receive barrage message after, then can call this interface by barrage message distribution to Subscriber.The present embodiment is barrage message subscribing person, then will receive barrage message;After receiving barrage message, then it can be put The display of barrage content is carried out to display area, then wherein pservermessage is then corresponding barrage message.
The present embodiment then calls the barrage display interface of UI display layer to show barrage.
DanmuUIShow pUIShow=new DanmuUIShow ();
pUIShow->showDanmu(pservermessage);Then its showDanmu is called to be shown to barrage In barrage display area.
}
The embodiment of the present invention then orders all message by the classification to type of message, then by message managing module Reader is managed, after receiving message, to be distributed to subscriber.Message management person energy in the case where not knowing subscriber It is enough managed, improves the treatment effeciency of link barrage, make user's unaware and then improve user experience.
Optionally, on the basis of above-mentioned Fig. 1 corresponding embodiment, the method for link barrage provided in an embodiment of the present invention Alternative embodiment in, message subscribing person abstraction interface of the determination based on C Plus Plus include: define message subscribing person pumping As interface class MessageObserver, class MessageObserver;Define the destructor function of the abstraction interface class Virtual~MessageObserver ();Define abstraction interface GetObserverMessageType;Define abstraction interface OnRecvPackMsg。
Optionally, on the basis of above-mentioned Fig. 1 corresponding embodiment, the method for link barrage provided in an embodiment of the present invention Alternative embodiment in, the object copies function that prevents of the determination abstraction interface includes: to define copy-constructor function At the existing function private:void operator=(const MessageObserver&) of empty real;The copy is constructed Function is defined as the existing function MessageObserver of privately owned empty real (const MessageObserver&).
Optionally, on the basis of above-mentioned Fig. 1 corresponding embodiment, the method for link barrage provided in an embodiment of the present invention Alternative embodiment in, the generation message subscribing person manages class, and the subscriber manages class for being managed to subscriber It include: to define a message management person class class ObserverManager;Std::multimap < std::string is generated, MessageObserver* > map_push_observer, and be managed by subscriber of the function multimap to message; The object map_push_observer of the function multimap is generated to store the subscriber.
Optionally, on the basis of above-mentioned Fig. 1 corresponding embodiment, the method for link barrage provided in an embodiment of the present invention Alternative embodiment in, it is described the interface of class is managed by the subscriber to carry out subscription sense to writing interface and provide subscriber The message of interest includes: by interface void SetMessageTypeObserver (MessageObserver*_ TaskObserver all subscribers registered in all subscriber's dealing message management objects) are supplied to;Pass through abstraction interface GetObserverMessageType obtains all type of messages that subscriber needs to subscribe to;Obtain return value _ cmdtypes, institute State return value store subscription in need type of message;Define an iterator objects std::set < std::string >::iterator itr;It initializes iterator itr=_cmdtypes.begin ();It is each to traverse to obtain to write for circulation A type of message;The insert interface of multimap container is called to be inserted into the subscriber into container.
Optionally, on the basis of above-mentioned Fig. 1 corresponding embodiment, the method for link barrage provided in an embodiment of the present invention Alternative embodiment in, it is described to the message subscribing person manage class carry out message parsing and by the message distribution being resolved to institute Some subscribers include: one message parser pDecoder of creation;By message storage to the buf in mq.read (buf, len) In;The type type that the buf obtains message is parsed by calling the message parser;An interface function is created to come pair The message is distributed to corresponding subscriber.
Optionally, on the basis of above-mentioned Fig. 1 corresponding embodiment, the method for link barrage provided in an embodiment of the present invention Alternative embodiment in, one interface of the creation includes: to pass through to be distributed the message to corresponding subscriber The count function of multimap container obtains subscriber's number n of the message;Define an iterator std::multimap < std::string,MessageObserver*>::itrator itr;Call find function corresponding to search from iterator Subscriber;After finding by subscriber storage into iterator itr;It is recycled by for and distributes the message one by one To each subscriber.
Embodiment two
It should be noted that on the basis of the above embodiments, the present invention can also have other implementations, for example, Based on Socket Client Design link solution, specific embodiment is as follows:
Step 1, the related data for creating socket, and linked with barrage server.Mobile terminal creation The related data of socket Socket, and linked with barrage server.Wherein, related data includes int sockfd= Socket (AF_INET, SOCK_STREAM, 0), address family servaddr.sin_family=ip, port numbers (servaddr.sin_port=htons (port) and system function int nRet=connect (sockfd, (struct sockaddr*)&servaddr,sizeof(servaddr))。
Step 2 determines network interruption object SocketBreaker.Mobile terminal determines network interruption object SocketBreaker, the SocketBreaker interrupt current link for triggering socket.Specifically, mobile terminal defines one A object function SocketBreaker pipe, object function SocketBreaker pipe are used to link socket and trigger It terminates current link.
Step 3, the selecting object select for creating network.
Mobile terminal creates the selecting object select of network, which is used to monitor the status information of socket.It moves Dynamic terminal creation SocketSelect select (pipe) object even monitors the status information of socket.Specifically, first will creation Socket and select object be associated so that select object is monitored socket.Select is specifically wrapped It includes: the function select.Exception_FD_SET (socket) being associated for the abnormal conditions to socket;For right The function select.Write_FD_SET (socket) that the read-write of socket is associated.When socket produce it is abnormal or Select can be monitored when can carry out transmission network data, or can read network data, for example, using function Int selectRet=select.Select (timeout) checks the state of current socket.Return value is judged, such as Fruit return value selectRet is 0, then it represents that the timeout time-out of setting, this link failure.
Step 4, creation event object event.
Mobile terminal creates event object event, which is used to notify the status information of socket.Mobile terminal wound Event object event is built, the status information of the socket for notifying upper layer current.
It specifically includes: function event.OnError (ConnectTimeoutErr), for calling event object Event's OnError function, and parameter is set as ConnectTimeoutErr, indicates link time-out error;Function Event.OnError (ConnectingErr), if return value selectRet < 0, then it represents that function is called in link error Event.OnError (ConnectingErr) notifies the current socket error in upper layer.Otherwise explanation this time link is successful, Then continue subsequent network to give out a contract for a project and packet receiving operation;Function event.OnConnect (), for calling event object event's OnConnect informs that upper layer current link is successful.
Step 5 creates the thread object Thread of socket and executes the execution function void__RunThread of Thread ()。
Mobile terminal creates the thread object Thread of socket and executes the execution function void__ of Thread RunThread().A thread object Thread thread_ is created first, while writing the function of thread execution Void__RunThread () is then based on Boost base library and binds thread execution function and pass to thread Function is executed, such as Thread (boost::bind (&MTcpclient::__RunThread, this)), so that this thread is held Row logic is then to take execution _ RunThread function function.After all data all initialize well, then calling is cut off out in movement The function Start of thread object starts the execution of this thread function, such as thread_.start ().
Step 6, the state that while circularly monitoring socket is created in executing function.
Mobile terminal creates the state of while circularly monitoring socket in executing function.Pass through creation (writing) While circulation monitors the state of socket constantly to handle dependent event.This while circulation entire logic function be In RunThread function logics, therefore the separate threads of socket can execute this section of code logic.One while of creation is followed Ring constantly receives the network data that sends over of barrage server from socket, and constantly will be objective from socket The network data that family end needs to send sends a barrage server.
First look at the state of socket, while (true) { int selectRet=select.Select ();
If then directly returning to waiting for next state, if (0=currently without readable data without writeable data, and without exception =selectRet) { continue;}
If current socket produces exception, inform that upper layer has currently gone out first IO read-write using event object event Mistake, if (0 > selectRet) { event.OnError (IOErr);
Terminate previous cycle, return by return;, whether it, which has exception, next otherwise is checked to socket;
Socket is judged by select object whether in abnormal set Exception_FD_ISSET, to know Whether current socket is abnormal;
if(select.Exception_FD_ISSET(socket)){event.OnError(IOErr);
And previous cycle return is terminated by return;}
Step 7 reads the data that the barrage server received in socket is sent.
Mobile terminal reads the data that the barrage server received in socket is sent.Mobile terminal judges that socket is The no network data that can read barrage server, detailed process is as follows: judged by select object socket whether It reads in set Read_FD_ISSET, to know whether current socket can read data;At this time by calling event pairs The OnRead of elephant informs that the current socket in upper layer has data that can read, so as to reading the network number of barrage server According to if (select.Read_FD_ISSET (socket)) { event.OnRead ();}
Step 8 will need the data sent to be sent to barrage server by socket.
The data sent will be needed to be sent to barrage server by socket.Mobile terminal judges whether socket can be with Network data is sent to the network data of barrage server, detailed process is as follows: judging that socket is by select object It is no to read Write_FD_ISSET inside set to know whether current socket send data;Pass through calling at this time The OnSend of event object informs that the current socket in upper layer can send network data, so as to by the data of client It is sent to barrage server, if (select.Write_FD_ISSET (socket_)) { event.OnSend ();Walk herein Whether the while circulation write in rapid constantly exception can occurs by monitoring socket, if can read data, if Ke Yifa Server is transmitted data to, so that constantly receiving barrage server data in program, sends data to barrage server.
In the embodiment of the present invention, the related data of socket is created, and linked with barrage server;It determines Network interruption object SocketBreaker, SocketBreaker interrupt current link for triggering socket;Create network Selecting object select, select are used to monitor the status information of socket;Event object event is created, event is for notifying The status information of socket;It creates the thread object Thread of socket and executes the execution function void__ of Thread RunThread();The state of while circularly monitoring socket is created in executing function;Read the bullet received in socket The data that curtain server is sent;The data sent will be needed to be sent to barrage server by socket.The embodiment of the present invention is right Barrage link uses asynchronous mode, the chain for creating an independent thread for a socket link to execute entire socket The process of link barrage is optimized in termination process, and after socket is received data, upper layer is informed by way of event, So that network data is only used on upper layer, the specific implementation of concern socket is not needed, the thought of hierarchical design is realized.It improves The efficiency of link barrage.
Embodiment three
It should be noted that on the basis of the above embodiments, the present invention can also have other implementations, for example, The design of the message queue on the upper layer based on socket, to handle the data that socket is received and the data that needs are sent, specifically Embodiment is as follows:
Step 1 determines the class of C++ to encapsulate the treatment process of network data.
The function of this step is then the upper layer identification code in corresponding step 1, will receive all event messages of event.It is first First the present embodiment designs the class of a c++ to encapsulate the treatment process of all-network data, and data will occur, and receives number According to, and the design that the mistake of socket is separated during entire socket, so that logic is relatively sharp, reception Data event is only responsible for the data received, and data event occurs and is only responsible for sending data, socket error event is only responsible for Socket error handle.Class TcpClient { wherein devises that a message queue is in need to store to be sent to service The network data of device, while can also realize the event message of all event.It is all a string of characters for each network data String, so each message is stored using the array of a Char* herein;And since message queue needs frequent storage net Network message takes out internet message, therefore for Data Structure and Algorithm, is relatively suitble to store using list structure, chain Table has the function of quickly being inserted into data and deletes data.}
Step 2 generates the container of Standard Template Library STL to store message.
The present embodiment is held using the container list chained list of Standard Template Library (standard template library, STL) Device stores internet message, stl::list<char*>listMessage;Define such object listMessage then It is the message queue storing process of the present embodiment.When needing to send a network data, then message team can be first stored to In column, because transmission the present embodiment of message uses asynchronous process, prevent when socket cannot send data, generation is lost Packet, and by message queue then can by the network data of transmission in need be cached, when socket can be sent Then data are taken out from message queue again when data to be sent.Specific storage message is as follows: calling the push_back of list class Function has then arrived the storage of a piece of news data in chained list, and the caudal end of chained list, listMessage.push_back are arrived in storage (sendbuff);By call list class front function then can from chained list take out chained list in foremost message data, It is as follows to take out message: char*buf=listMessage.front ();And need to call the pop_front function of list class Message data is extractd from chained list, listMessage.pop_front ().
Step 3, the OnRead event for creating event, OnRead expression have read the network data that barrage server issues.
The event functions that will receive bottom socket in step 1 include OnError event, OnRead event, OnSend Event.Void OnRead () { is then that can read network data when bottom code sends socket for OnRead event When, this layer identification code is notified that read network data.The present embodiment then can read socket with calling system function recv In network data, ssize_t ret=recv (socket, (char*) buf, len, 0);Wherein buf is read for storing The data got, len are then the length read.This function call is completed then store network data into buf, to complete The reception of one network data, can then store in message queue after receiving data;Define a message queue MessageQueue mq;Wherein mq is then message queue object, while the present embodiment supports multiple threads simultaneously toward message queue It is middle to be stored in the message collected, also support multiple threads to take message from message queue simultaneously.So the present embodiment defines one Mutex write_mutex;Mutex object write_mutex;Then one is defined to lock to lock Mutex object, ScopedLock lock(write_mutex_);Then message queue object is recalled to store the network data received, mq.write(buf,len);Expression stores a piece of news into message queue.The present embodiment then by all message received all It is put into message queue in mq.}
Step 4, the OnSend event for creating event, OnSend expression can send data to barrage server.
Void OnSend () { is then when bottom code finds that current socket can send network for OnSend event When data, then message can be taken out from message queue and be sent;All message for being sent to server will use herein One message queue cached, so that application layer can send data with multithreading.Define a message Queue MessageQueue mq2;Wherein mq2 is message queue object, and sending message is then constantly to take out from message queue Message is sent.In order to support multithreading the present embodiment to define a Mutex read_mutex;Mutex object read_ mutex;Then it defines one to lock to lock Mutex object, ScopedLock lock (read_mutex_);Then it adjusts again It is taken out with message queue object and the network data sent is needed to be sent, mq2.read (buf, len);To be needed Then message is carried out transmission send (socket, buf, len) using system function by the data buf of transmission;}
Step 5, the OnError event for creating event, OnError indicate socket in entire link either sending and receiving data When encounter mistake.
Void OnError (int nStatus) { is then when bottom code discovery is current for OnError event Mistake has occurred in socket link, then is notified that application layer, socket produces mistake, is handled, and give Specific status code.After receiving status code, in order to preferably design, so needing to distinguish status code, some states Code does not need to carry out reconnection, some status codes then need reconnection, specifically herein without limitation.}}
Mentality of designing of the present embodiment based on layering, upper layer is decoupling by the network transmitting-receiving progress of bottom, provides preferably Hierarchical design, Optimized Coding Based, logical process are relatively sharp.The Message Processing queue of the socket on upper layer is designed in the present embodiment, It handles the data received and the data that send of needs of socket, improves the treatment effeciency of link barrage.
Example IV
It should be noted that on the basis of the above embodiments, the present invention can also have other implementations, for example, Link solution is designed based on socket status code, whether design carries out reconnection, and specific embodiment is as follows:
Step 1, the mapping table for generating storage state code.
First there are many kinds of status codes, when socket when the error occurs, need to take the status code that currently generates to go the inquiry to be It is no to need to carry out reconnection.When it come to arrive the performance that inquiry then needs to consider inquiry.The present embodiment is held based on Standard Template Library STL The map container of device stores status code.Map container is then based on when inquiry, and then search speed can be very fast, map < int, bool>mapStatus;The present embodiment defines a map<int, bool>type object mapStatus.Wherein.First parameter Int is the key value of map container, and for storing the status code of socket, second parameter bool is for storing current state code It is no to need to carry out reconnection.Following all status codes are known, then needing that all status codes are marked and are stored In map container object.The status code that mistake is used to indicate in status code is alternatively referred to as error code.
Step 2 determines all possible state and status code in the entire link process of socket, status code with can The state of energy corresponds.
All status codes then include in the entire use process of entire socket issuable all situations it is as follows:
KInitErr indicates initialization error code.KSocketThreadStart indicates socket initialization thread. KSocketThreadStartErr indicates socket initialization thread error code.KTcpConnectIpErr, indicate socket Error code is produced when linking ip.KTcpConnectTimeoutErr indicates that socket produces time-out.KTcpIOErr, table Show that socket sends data and produces io error code.KTcpDisConnectedbyRemote indicates that socket is closed by server Link is closed.KTcpDisConnected indicates that socket link is disconnected.Above all of status code the present embodiment is made It is indicated with integer.And all error codes cannot have identical numerical value.
The present embodiment is designed using a skill enumerated variable type of C Plus Plus, so that compiler can help to examine It is unduplicated for looking into the value of all status codes.
Enum SocketStatus kInitErr=1, kSocketThreadStart,
kSocketThreadStartErr,kTcpConnectIpErr,kTcpConnectTimeoutErr,
kTcpIOErr,kTcpDisConnectedbyRemote,kTcpDisConnected,
};
The present embodiment defines an enumerated variable enum SocketStatus;All status codes in enumerated variable All it is included.And 1 is assigned a value of to first status code, then subsequent others status code then can be automatically in first shape Add 1 on the basis of state code, so that the value of all status codes can not repeat.Such as the value of kSocketThreadStart is then The value for being 2, kSocketThreadStartErr is then 3, and specific details are not described herein again.
Step 3 stores status code into mapping table.
For all these status codes, error code is produced when having plenty of link, is had plenty of in data transmission procedure Error code is produced, has plenty of and belongs to normal closing socket link.It is then needed to be treated differently when so for reconnection, some It is to have sent mistake, carries out reconnection at once, so that user can see barrage at once, prevents barrage link from disconnecting;And Some belong to client normal switching-off or server normal switching-off client does not need to carry out reconnection.It is following then need pair The assignment of mapStatus container object progress status code.Specific code is illustrated below.
MapStatus [kInitErr]=true;This journey code indicates that key value is stored into mapStatus container is KInitErr, and whether reconnection is set as true, indicates that this status code needs reconnection.
MapStatus [kSocketThreadStart]=false;This journey code indicates to deposit into mapStatus container Storage key value is kSocketThreadStart, and whether reconnection is set as false, due to only having carried out initialization so not Need reconnection.
MapStatus [kSocketThreadStartErr]=true;This journey code is indicated into mapStatus container Storage key value is kSocketThreadStartErr, and whether reconnection is set as true, due to being creation thread mistake, So needing to carry out reconnection.
MapStatus [kTcpConnectIpErr]=true;This journey code indicates to store into mapStatus container strong Value is kTcpConnectIpErr, and whether reconnection is set as true, due to producing mistake when being connection IP, so needing Carry out reconnection.
MapStatus [kTcpConnectTimeoutErr]=true;This journey code is indicated into mapStatus container Storage key value is kTcpConnectTimeoutErr, and whether reconnection is set as true, due to producing time-out error, institute To need to carry out reconnection.
MapStatus [kTcpIOErr]=true;This journey code indicates that key value is stored into mapStatus container is KTcpIOErr, and whether reconnection is set as true, due to producing reading and writing data mistake, so needing to carry out reconnection.
MapStatus [kTcpDisConnectedbyRemote]=false;This journey code indicates to hold toward mapStatus It is kTcpDisConnectedbyRemote that key value is stored in device, and whether reconnection is set as false, due to being that server closes Link is closed, so not needing to carry out reconnection.
MapStatus [kTcpDisConnected]=true;This journey code indicates to store into mapStatus container strong Value is kTcpDisConnected, and whether reconnection is set as true, is disconnected due to being that link is unstable, thus need into Row reconnection.So far, the value storage of all status codes has been arrived in mapStatus container, and has been to each status code No progress reconnection all set whether reconnection.
Step 4 judges whether the inquiry for needing to carry out reconnection according to status code.
Have query interface when socket send mistake after, according to error code come inquire whether the interface of reconnection, if need Reconnection is wanted then to carry out reconnection automatically, otherwise break link.If there is other new status codes need to be added, then can exist first A state code type is added in enum SocketStatus, assignment operation then is carried out to it in mapStatus container. Next in order to design better encapsulation, so the present embodiment can design an interface whether to provide one status code of inquiry It needs to carry out reconnection.Detailed process is as follows:
bool GetRetryFlag(int nStauts)
{ wherein, interface return value is bool variable, wants reconnection for true expression, indicates not reconnection for false;Interface Title is GetRetryFlag;Wherein, only one parameter int nStauts indicates the status code of inquiry;
Then the query interface find interface using map container is needed:
map<int,bool>::iterator itr;The iterator of a map container is defined first;
Itr=mapStatus.find (nStauts);Then its find interface is called to inquire current state code, is inquired As a result it is then stored in itr iterator, wherein the value value of iterator is then end value.
retrun(*itr).value;So then using the value value of iterator as returning the result.
}
There is status code query interface, then can obtain whether current state needs to carry out reconnection by inquiring, from And basic technical support is provided to application layer, application layer is made whether reconnection according to query result.
The embodiment of the present invention, designed based on socket status code link barrage scheme, when mobile terminal network not When stabilization is disconnected barrage, Auto-reconnect technology reconnection barrage is also can be used in mobile terminal, improves the processing of link barrage Efficiency makes user's unaware and then improves user experience.
Embodiment five
It should be noted that on the basis of the above embodiments, the present invention can also have other implementations, for example, Link solution is designed based on the error code that server issues, whether design carries out reconnection, and specific embodiment is as follows:
In barrage link process, the identity for the client that barrage server can link barrage is verified, while The agreement of link can be checked, comprising: detection protocol type checks protocol fields.Each field can also be judged simultaneously It is whether legal, if having a forbidden character, or whether wrong agreement etc..It may also can simultaneously for client in link process Some abnormal datas etc. are sent, therefore barrage server can return to different error codes to the different situations of client.For example, Client logs in barrage server, and the token field used is not the token that client account number cipher logs in, at this time bullet Curtain server, which can return to specific error code, indicates link token mistake.
Specifically, when such as viewing live streaming, the room number given of link barrage server be not present in live streaming platform, so Barrage server can also return to particular error code at this time;When client exits room, the chain of barrage server will disconnect at this time It connects, barrage server can return to specific error code at this time;If the unstable networks of same active user, when client is long Between server is not given to send specific phychology data packet, server judges that client network is unstable, also will be considered that client It is lost link, can also return to specific error code at this time;When client and server carry out network data transmission, Ke Nengye The data for being sent to server there are certain probability client are incorrect, then server can also send particular error code to client End;It is also possible to have the case where account multiple equipment for user, the same account is stepped on using multiple and different equipment simultaneously The same direct broadcasting room is recorded, server can also return to specified error code.Therefore special treatment is needed for different error codes, only There are some error codes just to need to carry out reconnection.Concrete implementation mode is as follows:
Step 1, generation error code message subscribing person's class ErrorMessageObserver.
Generate the subscriber of a server error message, class ErrorMessageObserver:public { it must realize all abstraction interface functions of MessageObserver, public:const to MessageObserver Std::set < std::string>&GetObserverMessageType () { defines a static container object first Types, static std::set<std::string>types;If types stored subscription in need message Then directly return.if(!types.empty()){return types;Otherwise without being stored in the message subscribed to, types.insert(error_TYPE);By calling insert function that can then be inserted into a message class into container object Type.If error message then subscribes to error_TYPE in the present embodiment.}
Step 2, the interface for determining error code message subscribing person.
Realize another abstraction interface OnRecvPackMsg.void OnRecvPackMsg(const std:: String&_cmdtype, const char*pservermessage) { when message subscribing distribution management module receives error message Afterwards, then it can call this interface that error message is distributed to subscriber, the present embodiment is error message subscriber, then will receive clothes Business device sends over all error messages, then wherein pservermessage is then corresponding barrage message.
It is parsed firstly the need of to message, the error code of message is also obtained from error message.Such as receive one together One account will receive server message when logging in multiple equipment and the same direct broadcasting room of entrance is as follows: type@= @=500 error/code;Wherein type@=error indicates that the type of message of this message is error.The wherein table of code@=50 The error code for showing this message is 500.
Step 3 parses message.
After receiving message, need to parse message.Firstly the need of the resolver of one message of creation, pDecoder MessageDecoder*pDecoder=new MessageDecoder ();Then the Parse interface of resolver is called to come pair Message is parsed, pDecoder- > Parse (pservermessage);After being parsed, need to obtain its code field Value, so that the value of error code is obtained, int errorcode=pDecoder- > GetItem (" code ");Call its GetItem Interface is assigned to errorcode variable to obtain the value of the error code of code field.After having obtained errorcode, Need errorcode to implement corresponding logic function: the present embodiment can classify to errorcode first, some It needs to carry out reconnection, some do not need to carry out reconnection, some need individually to handle again.Need the mistake of reconnection Code book embodiment can be put it in an enumerated variable, and { KDisconnect=50 indicates error code to enum RetryCode It is 50, since unstable networks cause link to lose;KDataError=60 indicates that error code is 60, due to its data field It loses;KIOError=70 indicates that error code is 70, due to error in data in transmission process.};So for such error code Then all need reconnection.
Step 4, generation error code map container and error code is associated.
Same the present embodiment can design a map container to store the error code of reconnection, when server has sent mistake After message, then the error code of reconnection can be inquired.Similarly define the error code that another map container storage does not need reconnection.
The present embodiment defines a mapRetry container object, map<int, bool>mapRetry.mapRetry [KDisconnect]=true;MapRetry [kDataError]=true;MapRetry [kIOError]=true;For The operation of not reconnection is as follows: { kTick=500 indicates that error code is 500, due to its same account to enum NotRetryCode It number logs in multiple equipment while logging in the same direct broadcasting room, barrage server can kick a client off.It not can be carried out then at this time Reconnection.KClientDisconnect=501 indicates that error code is 501, indicates that client has actively closed current link, because This does not need to carry out reconnection.
}
Similarly define the error code that another map container storage does not need reconnection.
map<int,bool>mapNotRetry;
MapNotRetry [kTick]=false;
MapNotRetry [kClientDisconnect]=false.
Step 5 determines that the error code of specific message carrys out reconnection logic.
After receiving an error message, it is necessary first to whether need reconnection according to error code to inquire, then inquire again Whether reconnection is not needed, and specific process is as follows:
map<int,bool>::iterator itr;
An iterator is defined first.
Itr=mapRetry.find (errorcode);
Then the error code obtained from error message is used to be inquired.
If (itr==mapRetry.end ())
Illustrate not find in reconnection error code;
It is following then require to look up the error code for not needing reconnection;
Itr=mapNotRetry.find (errorcode);
If (itr==mapNotRetry.end ())
If not finding explanation also not in the error code for not needing reconnection, illustrate that these error codes are needed into one Step handle;
If (errorcode==800)
Wherein error code 800 indicates room number mistake, and client then can obtain room from global information center and believe at this time Breath.
Int nRoomId=Datacenter ():: instance () -> getRoomid ();
The present embodiment can store direct broadcasting room relevant information into data center Datacenter, when link barrage server It was found that when room number mistake then room number can be obtained from information centre again to carry out reconnection.
Carry out reconnection after obtaining all again;
Int nRet=connect (sockfd, (struct sockaddr*) &servaddr, sizeof (servaddr));
The code of step 1 is continued to use to carry out network linking;
Else if (errorcode==900)
Wherein error code 900 indicates that the token of current link is failed, and correctly doing rule at this time is to re-request Then token carries out reconnection again, then client will use HTTP request then to obtain new token at this time, get new Barrage link is carried out again after token.
Token=http.get ()
The present embodiment obtains token data by the get function of http, after obtaining token, then again carry out weight Even.
}
{ explanation has found else, illustrates not needing to carry out reconnection;
The Break function of pipe object before the present embodiment can then call disconnects current network linking;
pipe.Break();
}
{ explanation has found else, then carries out reconnection;
Int nRet=connect (sockfd, (struct sockaddr*) &servaddr, sizeof (servaddr));The code of step 1 is continued to use to carry out network linking.
}
The embodiment of the present invention, and some error codes based on mobile terminal in discovery barrage link process, mobile terminal Also Auto-reconnect technology reconnection barrage can be used, improve the treatment effeciency of link barrage, make user's unaware and then improve User experience.
Embodiment six
It should be noted that on the basis of the above embodiments, the present invention can also have other implementations, for example, Network Environment designs link solution, and specific embodiment is as follows:
With popularizing for Internet protocol 6 (internet protocol version 6, IPV6), for mobile terminal For, the network of Internet protocol 4 (internet protocol version 4, IPV4) can be used, also can be used mutually The network of networking protocol 6 (internet protocol version 6, IPV6), and if barrage server itself is only supported The network of IPV4 then needs the address conversion that the client of mobile terminal is carried out IPV6 at the address of IPV4, passes through IPV4's Linked server is carried out in address.When being necessary to ensure that support link barrage, mobile terminal can also chain mutually in the environment of IPV6 The barrage server of networking protocol 4 (internet protocol version 4, IPV4).When based on multiple Internet protocols In the case of (internet protocol, IP) or domain name, available IP how is quickly selected, how to allow user to see as soon as possible Become primary problem to barrage.The present invention provides a solution, the specific steps are as follows:
Step 1 determines network type belonging to barrage server.
When client (installation is on mobile terminals) starts to link barrage server, since the IP of server is IPV4, thus regardless of it is local is IPV4 or IPV6, require to be converted into the network address of IPV4 to be linked, then client End then needs to judge to be currently the network of IPV4 or the network of IPV6, while to be also converted into IPV4 if it is the network of IPV6 Network.
Step 2 judges that current network environment is IPV4 or IPV6.
Current embodiment require that judging that current network is the network environment of IPV6, if it is explanation is IPV6, if It is not to illustrate it is currently IPV4.The present embodiment goes to link by defining the network address of an IPV6, if successfully explanation is worked as Preceding support is IPV6 network.For the IP address 2000::0 of IPV4 the present embodiment selection server, and for this implementation of IPV6 Example then uses 2000::0 to go to link as the address of server.It is implemented as follows:
Define the address information variable struct sockaddr_in addr of a socket;Addr.sin_len= Sizeof (sockaddr_in), addr.sin_family=AF_INET6, wherein being this time shown to be using IPV6, then to it Assignment is carried out, wherein port numbers use 80 ports, and then IP uses 2000:: being the address of an IPV6, addr.sin_port =80, addr.sin_addr.s_addr={ // 2000::0x20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }.
Then a socket is created, and uses User Datagram Protocol (user datagram protocol, UDP) Agreement, because whether the IP that the present embodiment is test current server can connect, the present embodiment uses UDP, because The speed ratio of UDP is very fast, int s=socket (pf, SOCK_DGRAM, IPPROTO_UDP).
Then calling system function connect is linked, int ret=connect (s, addr, addrlen);If Return value ret illustrates to link successfully for 0, otherwise link failure.If linked, successfully explanation is current to support IPV6, if successful Illustrate to be currently IPV6 network environment, be otherwise IPV4 network environment, link barrage clothes then can be directly carried out if it is IPV4 Business device.
Step 3, by the network address translation of IPV6 at the network address of IPV4.
It then also needs to carry out address conversion if it is IPV6, by system function socket_inet_ntop to the ground of IPV6 Location is converted into the address of IPV4.Be implemented as follows: the variable for defining an IPV4 first is with being used to store the IPV4 after conversion Location, char ipv4 [100]={ 0 };Following then calling system function socket_inet_ntop is converted, wherein parameter Addr.sin6_family indicates IPV6 address protocol, and wherein parameter addr.sin6_addr is the address of the IPV6 of input;Its Middle parameter IPV4 can then store conversion after as a result, socket_inet_ntop (addr.sin6_family, & (addr.sin6_ addr),ipv4,sizeof(ipv4)).Mobile terminal has determined whether current network environment is IPV4 or IPV6, if it is IPV6 is since server uses the address of IPV4 so needing to convert address, thus movement according to the present embodiment Terminal applies can also be linked to the barrage server of IPV4 under the network environment of IPV6.
Step 4 connects barrage server based on the address IPV4 after conversion.
When by the network address translation of IPV6 at IPV4 network address after, then mobile terminal can be directly connected to barrage clothes Business device.Establish the connection with server, int sockfd=socket (AF_INET, SOCK_STREAM, 0).Address family Servaddr.sin_family=ip;Port numbers (host byte sequence to network bytes sequence), servaddr.sin_port= htons(port);Calling system function connect starts to connect barrage server, then can directly be connected by connect Meet barrage server, int nRet=connect (sockfd, (struct sockaddr*) &servaddr, sizeof (servaddr))。
The embodiment of the present invention, the network address for being IPV4 by the network address translation of IPV6, it is ensured that mobile terminal is in IPV6 In the environment of can also chain only support IPV4 barrage server, improve link barrage treatment effeciency.
Embodiment seven
It should be noted that on the basis of the above embodiments, the present invention can also have other implementations, for example, The network switching of current network environment is monitored, reconnection design link solution, specific implementation are carried out based on monitored results Under such as:
Since mobile terminal device is usually mobile and PC equipment is widely different, process may with user into Line position sets movement, with the mobile switching that can then generate network.For example, WIFI use at home, then can be switched to 4G after going out, Network that may also be weak to signal for the very strong network switching of signal, and for viewing live streaming, need as far as possible discover net Network transformation, thus early link.Specifically, then needing to monitor current network from 4G network switching to WIFI network It is converted, to disconnect current network linking, reuses new network and linked, it can be faster new Barrage server is chained in network.And when from having network or strong signal network switching to no signal network or weak signal net When network, in order to save electricity, the overtime reconnection using network bottom layer is then needed at this time, and is set as more for a long time Time-out, allow bottom-layer network to carry out reconnection, electricity saved with this.The present embodiment is then linked according to android system to design The method of barrage, the specific steps are as follows:
Step 1 defines a network linking type to store current network type, and generates the state of network type Code.
The present embodiment defines a network linking type to store current network type, determines an enumerated variable to deposit Network type is stored up, NetStatus enumeration type is defined as.
enum NetStatus{
KNONET=1,
kWIFI,
k4G,
};There is defined kNONET to indicate currently without network, and is assigned a value of 1;Defining kWIFI indicates current net Network is WIFI, then automatic assignment is 2;Defining k4G indicates that current network is 4G network, then automatic assignment is 3, defines network State NetStatus curStatus.
Step 2, the monitoring class for generating network state in android system.
For android system, monitoring current network variation needs first to write a sub- Similar integral in system BroadcastReceiver class, and network event therein is monitored.It is defined in the present embodiment NetworkChange class is inherited in the BroadcastReceiver of system, that is, generates succession in system The subclass NetworkChange class of BroadcastReceiver class.
public class NetworkChange extends BroadcastReceiver{
Following then heavily loaded its interface receives network change;
@Override
public void onReceive(Context context,Intent intent){
Whether judgement has currently connected network;
if(ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction ())){
Then current network state is judged by ConnectivityManager attribute;
Then NetworkInfo object info, NetworkInfo an info is defined;
Then the current network information is obtained.It is specific then can be obtained by system function getParcelableExtra Current network information, and incoming parameter is ConnectivityManager.EXTRA_NETWORK_INFO.
Info=intent.getParcelableExtra (
ConnectivityManager.EXTRA_NETWORK_INFO);
After obtaining info information, judgement is currently WIFI, and 4G is again without network;
If (info.getType ()==ConnectivityManager.TYPE_WIFI)
Pass through the available current network type of the interface getType of info;
If network type is ConnectivityManager.TYPE_WIFI, that indicate current link is WIFI, and will Network state type is set as WIFI network;CurStatus=kWIFI;
Else if (info.getType ()==ConnectivityManager.TYPE_MOBILE)
If that current link is not WIFI, continue to judge that its type is ConnectivityManager.TYPE_MOBILE, if so, show current link is the 4G network of mobile phone.
CurStatus=k4G;
Else { curStatus=kNONET;
It indicates to use currently without network, is then in network off-state.
}
}
}
}
Step 3 carries out instantiation and system registry to monitoring class.
Calling system function is also needed to be registered to monitoring current network.
Firstly the need of one IntentFilter filter=new IntentFilter () of creation;Then pass through calling The addAction function of IntentFilter is added the monitoring to network, filter.addAction (ConnectivityM anager.CONNECTIVITY_ACTION);Wherein being passed to parameter is ConnectivityManager.CONNECTIVITY_ ACTION.Then the object of a NetworkChange class, NetworkChange net=new are instantiated NetworkChange();The registerReceiver function of following calling system carrys out registered network monitoring, registerReceiver(net,filter);To realize the monitoring to network.
Step 4 is monitored by status code of the registerReceiver function to network type, and according to status code Situation of change link barrage server.
Next it needs to change according to current network to do some adjustment to barrage link.We, which monitor network and obtain, works as Preceding network state, then the present embodiment can be compared with network state before, if network state there is no variation, The link of current barrage is not operated then.It needs to come according to current state variation to net if network state is changed Network is changed.The defined variable NetStatus prevStatus=kNONET in program starting;And its value is initialized For the state of no network.After having checked primary network state, then current network can be assigned to it come the net before storing Network state.PrevStatus=curStatus.When for network switching, we understand foundation before network and present network Whether state is operable to judge to link barrage.
If (prevStatus==curStatus)
If illustrating network, there is no variations, then as current network state with network state is before Barrage link does not change.
Else if (prevStatus==kNONET)
If being before no network, now with network, then need to carry out barrage link.
The code of step 1 is continued to use to carry out network linking, int nRet=connect (sockfd, (struct sockaddr*)&servaddr,sizeof(servaddr));
Else if (prevStatus==kWIFI)
If being to have the state of WIFI, and present network state is changed before, if being 4G network now It needs to disconnect existing barrage link as soon as possible, re-starts link using new network.Before the present embodiment can then call The Break function of pipe object disconnects current network linking.
After disconnecting network, pipe.Break ();Carry out reconnection operation again is needed, the code for continuing to use step 1 comes Carry out network linking, int nRet=connect (sockfd, (struct sockaddr*) &servaddr, sizeof (servaddr));
Else if (prevStatus==k4G)
If being to belong to 4g network, and be now WIFI before, then it is also required to carry out network disconnection at once, and again Link new network.The Break function of pipe object before the present embodiment can then call disconnects current network linking.
After disconnecting network, pipe.Break ();Carry out reconnection operation again is needed, the code for continuing to use step 1 comes Carry out network linking, int nRet=connect (sockfd, (struct sockaddr*) &servaddr, sizeof (servaddr));
}
}
}
The embodiment of the present invention, when from having network or strong signal network switching to no signal network or weak signal network When, using the overtime reconnection of network bottom layer, and it is set as more prolonged time-out, allows bottom-layer network to carry out reconnection, with this Electricity is saved, the treatment effeciency of link barrage is improved.
Embodiment eight
It should be noted that on the basis of the above embodiments, the present invention can also have other implementations, for example, Link solution is designed based on quickly switching or selecting the IP that can be linked, specific embodiment is as follows:
In order to which the client ensured on mobile terminal can chain barrage server (server), usual server can be given The IP list of multiple servers selects to use for client out, and client can arbitrarily select the IP of a server as oneself Linked server IP.Existing rule of doing is the clothes selected an IP from IP list to be linked, but work as an IP There are failure, perhaps this network line breaks down and then needs client quickly to switch or select can to link business device IP.And for server there is also there is domain name in the case where, needing to parse domain name obtains more IP, selects chaining needs More suitable IP is linked out, to improve entire link speed.
Step 1, the data structure for defining IP and port.
Assuming that existing IP is listed as follows: ip1:119.23.45.6port:4002ip2:118.34.32.7port: 4002ip3:120.45.33.1port:4008ip4:121.55.23.8port:2009ip5:130.55.23.8port:4009; The present embodiment defines the structure of an ip and port, strcunt ipportitem { string ip;int port;Structure In include ip data and port data, then each ip and port can be stored by this ipportitem.
Step 2 determines barrage server domain name.
While providing barrage server ip, in order to improve the success rate of user's connection, link speed, domain name have There is the function that preferred network recently is carried out according to user's current geographic position.And also to prevent from not linking, provide One domain name danmu.dy.com client, needs quickly to pick out the ip that can be connected from these ip, so that subsequent can More quickly to connect barrage server.
Step 3, selection support the balanced IP of barrage server load.
In order to ensure that it is certain random that IP client that server provides can carry out, so that all clients will not It chooses the same IP and server is caused to collapse because of load too high.There is also some possibility, some ports of client simultaneously It is closed without server can be chained.Therefore upset at random and need to select the link that different ports is attempted.
Step 4 parses IP address according to barrage server domain name.
Client needs to parse domain name first, parses more IP address.Then the IP that translates domain names into and The IP that server issues is upset at random together, and system provides getaddrinfo function to translate domain names into IP address. The present embodiment can realize the conversion of domain name then with calling system function.The result of domain name transfer function can then be stored In struct addrinfo structure, so needing to define corresponding structure.Struct addrinfo hints, * single, result;The present embodiment defines 3 such structure variables.It needs to empty variable, memset (&hints, 0, sizeof (hints));Hints.ai_family=PF_INET;Hints.ai_socktype=SOCK_STREAM;Then to hints Information carries out assignment, and the present embodiment is to obtain the corresponding ip of domain name, so socktype is assigned a value of SOCK_STREAM.It connects down Carry out calling system function getaddrinfo to realize the parsing of domain name.getaddrinfo(host_name,NULL,&hints,& result);Wherein needing incoming parameter host_name is then domain name, danmu.dy.com function call in corresponding the present embodiment After the completion, it as a result can then store in hints and result;And a domain name parses multiple ip, then with chained list Form is stored into result.Next for circulation is write to traverse the ip list parsed.For (single= result;single;Single=single- > ai_next) { result is stored in result, and next result is then in ai_ In next structure, the present embodiment is obtained by traversing.Const char ip=single- > ai_addr.ip;In each chain In table structure, data are stored in this attribute of ip.
Step 5 generates a container object ipportitem item to store the multiple IP got.
The present embodiment designs vector<ipportitem>vecip;The present embodiment defines a container object to deposit Store up the ip, ipportitem item got;
An item is created first, and assignment, item.ip=ip then are carried out to item;Item.port=port; vecip.push_back(item);By calling the push_back function of container then to arrive ip storage in container, while It needs also to store by ip and port above.ipportitem item1;Item1.ip=119.23.45.6; Item1.port=4002;vecip.push_back(item1);ipportitem item2;Item2.ip= 118.34.32.7;Item2.port=4002;vecip.push_back(item2);ipportitem item3;item3.ip =120.45.33.1;Item3.port=4008;vecip.push_back(item3);ipportitem item4; Item4.ip=121.55.23.8;Item4.port=2009;vecip.push_back(item4);ipportitem item5;Item5.ip=121.55.23.8;Item5.port=4009;vecip.push_back(item5);This is arrived All ip and port are all stored and arrived in vecip container.
Step 6 carries out random and upsets to the multiple IP got.
Next it needs to upset the data in vecip at random.Corresponding interface is provided for STL container Random_shuffle upsets the data in STL container at random.It is implemented as follows: random_shuffle (vecip.begin(),vecip.end());After calling this function of completion, all ip in container have been disturbed, After upsetting, the subsequent strategy of the present embodiment is to select 3 ip every time to be linked, therefore not have identical end in best one group of ip Slogan, if there is the identical exchange that can then carry out position with subsequent ip.
Step 7, according to IP link barrage server random and after upsetting.
Existing method is to carry out attempting to remove linked server by ip one by one and port.Such situation there may be times when The not upper time loss of the chain as caused by time-out is long.And the present embodiment then can successively select from container 3 ip come into Row attempts link, and the time-out that each ip is arranged 4 seconds disconnects other 2 ip's if having one to connect in 3 ip at once Link.The present embodiment is initiated first ip and is linked when starting link first.Create web socket socket;int Sockfd=socket (AF_INET, SOCK_STREAM, 0) establishes the connection with server;Address family is created, Servaddr.sin_family=vecip [0] .ip;It creates port numbers (host byte sequence to network bytes sequence), Servaddr.sin_port=htons (vecip [0] .port);Then it is linked, int nRet=connect (sockfd,(struct sockaddr*)&servaddr,sizeof(servaddr));In 4 seconds, if link returns , then illustrate successful connection, illustrates that this ip link speed ratio is very fast, can be used, it is subsequent, it is linked based on this IP;And If without returning successfully or failing, the present embodiment can then be selected from vecip for this link from starting to be linked to 4 seconds Second ip is selected to be linked.Int sockfd1=socket (AF_INET, SOCK_STREAM, 0) establishes the company with server It connects;Create address family, servaddr1.sin_family=vecip [1] .ip;Create port numbers (host byte sequence to network word Save sequence), servaddr1.sin_port=htons (vecip [1] .port);Then it is linked, int nRet=connect (sockfd1,(struct sockaddr*)&servaddr1,sizeof(servaddr1));If similarly having spent 4 seconds not having There is the link for returning and opening third ip;Int sockfd2=socket (AF_INET, SOCK_STREAM, 0) is established and service The connection of device;Create address family, servaddr2.sin_family=vecip [2] .ip;Creating port numbers, (host byte sequence arrives Network bytes sequence), servaddr2.sin_port=htons (vecip [2] .port);So the present embodiment is opened in 12 seconds The link of 3 groups of ip, int nRet=connect (sockfd1, (struct sockaddr*) &servaddr2, sizeof are opened (servaddr2));If there is the link of any one ip returns, the present embodiment can all disconnect the link of other ip.To Illustrate that the ip linked circuits first returned are more preferable, link speed is faster.
The present embodiment then can successively select from container 3 ip to carry out trial link, than traditional approach more rapidly Connect barrage server.Improve the treatment effeciency of link barrage.
The embodiment of the present invention is described from the angle of the method for link barrage above, below from the angle of mobile terminal The embodiment of the present invention is described in degree.
Referring to Fig. 2, Fig. 2 is a kind of embodiment schematic diagram of possible mobile terminal provided in an embodiment of the present invention, packet It includes:
First determination unit 201, for determining message subscribing person's abstraction interface based on C Plus Plus;
Second determination unit 202 prevents object copies function for determine the abstraction interface;
Generation unit 203, for generating message subscribing, person manages class, and the subscriber manages class and is used to carry out subscriber Management;
Subscriber units 204, for being carried out by the interface of subscriber management class to interface offer subscriber is write Subscribe to interested message;
Dispatching Unit 205 is parsed, for managing class progress message parsing to the message subscribing person and disappearing what is be resolved to Breath is distributed to all subscribers;
Third determination unit 206, for determining the subscriber of each message.
Optionally, in some possible implementations, the first determination unit 201 is specifically used for: defining message subscribing person Abstraction interface class MessageObserver, class MessageObserver;Define the destructed letter of the abstraction interface class Number virtual~MessageObserver ();Define abstraction interface GetObserverMessageType;Define abstraction interface OnRecvPackMsg。
Optionally, in some possible implementations, the second determination unit 202 is specifically used for: by copy-constructor function It is defined as the existing function private:void operator=(const MessageObserver&) of empty real;By the copy Constructed fuction is defined as the existing function MessageObserver of privately owned empty real (const MessageObserver&).
Optionally, in some possible implementations, generation unit 203 is specifically used for: defining a message management person Class class ObserverManager;Generate std::multimap<std::string, MessageObserver*>map_ Push_observer, and be managed by subscriber of the function multimap to message;Generate the function multimap's Object map_push_observer stores the subscriber.
Optionally, in some possible implementations, subscriber units 204 are specifically used for: passing through interface void SetMessageTypeObserver (MessageObserver*_taskObserver) is supplied to all subscriber's dealing message All subscribers registered in management object;Subscriber is obtained by abstraction interface GetObserverMessageType to need to order All type of messages read;Obtain return value _ cmdtypes, the return value store subscription in need type of message; Define an iterator objects std::set<std::string>:: iterator itr;Initialize iterator itr=_ cmdtypes.begin();For circulation is write to traverse to obtain each type of message;Call multimap container Insert interface is inserted into the subscriber into container.
Optionally, in some possible implementations, parsing Dispatching Unit 205 is specifically used for: one message solution of creation Parser pDecoder;By message storage into the buf in mq.read (buf, len);It is solved by calling the message parser Analyse the type type that the buf obtains message;An interface function is created to be distributed the message to corresponding subscription Person.
Optionally, in some possible implementations, parsing Dispatching Unit 205 is specifically also used to: passing through multimap The count function of container obtains subscriber's number n of the message;Define an iterator std::multimap < std:: string,MessageObserver*>::itrator itr;Find function is called to search corresponding subscription from iterator Person;After finding by subscriber storage into iterator itr;It is recycled by for and is distributed to the message often one by one One subscriber.
Referring to Fig. 3, Fig. 3 is the embodiment schematic diagram of electronic equipment provided in an embodiment of the present invention.
As shown in figure 3, the embodiment of the invention provides a kind of electronic equipment, including memory 310, processor 320 and deposit The computer program 311 that can be run on memory 320 and on the processor 320 is stored up, processor 320 executes computer program It is performed the steps of when 311 and determines message subscribing person's abstraction interface based on C Plus Plus;Determine preventing for the abstraction interface Object copies function;It generates message subscribing person and manages class, the subscriber manages class for being managed to subscriber;Pass through institute The interface for stating subscriber's management class carries out subscribing to interested message to interface offer subscriber is write;To the message subscribing Person manages class and carries out message parsing and by the message distribution being resolved to all subscribers;Determine the subscription of each message Person.
Optionally, in a kind of possible embodiment, the processor is specifically used for: defining the abstract of message subscribing person and connects Mouth class MessageObserver, class MessageObserver;Define the destructor function virtual of the abstraction interface class ~MessageObserver ();Define abstraction interface GetObserverMessageType;Define abstraction interface OnRecvPackMsg。
Optionally, in a kind of possible embodiment, the processor is specifically used for: copy-constructor function is defined as sky The function private:void operator=(const MessageObserver&) of realization;By the copy-constructor function It is defined as the existing function MessageObserver of privately owned empty real (const MessageObserver&).
Optionally, in a kind of possible embodiment, the processor is specifically used for: defining message management person's class class ObserverManager;Generate std::multimap<std::string, MessageObserver*>map_ Push_observer, and be managed by subscriber of the function multimap to message;Generate the function multimap's Object map_push_observer stores the subscriber.
Optionally, in a kind of possible embodiment, the processor is specifically used for: passing through interface void SetMessageTypeObserver (MessageObserver*_taskObserver) is supplied to all subscriber's dealing message All subscribers registered in management object;Subscriber is obtained by abstraction interface GetObserverMessageType to need to order All type of messages read;Obtain return value _ cmdtypes, the return value store subscription in need type of message; Define an iterator objects std::set<std::string>:: iterator itr;Initialize iterator itr=_ cmdtypes.begin();For circulation is write to traverse to obtain each type of message;Call multimap container Insert interface is inserted into subscriber into container.
Optionally, in a kind of possible embodiment, the processor is specifically used for: one message parser of creation pDecoder;By message storage into the buf in mq.read (buf, len);By calling the message parser to parse State the type type that buf obtains message;An interface function is created to be distributed the message to corresponding subscriber.
In the specific implementation process, when processor 320 executes computer program 311, the corresponding embodiment of Fig. 1 may be implemented Middle any embodiment.
The embodiment of the present invention determines message subscribing person's abstraction interface MessageObserver based on C Plus Plus;It determines The abstraction interface prevents object copies function;It generates message subscribing person and manages class ObserverManager;It is ordered by described The interface that reader manages class ObserverManager carries out subscribing to interested message to interface offer subscriber is write;It is right The message subscribing person manages class and carries out message parsing and by the message distribution being resolved to all subscribers;Determine each The subscriber of message.The embodiment of the present invention then disappears to all by the classification to type of message, then by message managing module Breath subscriber is managed, after receiving message, to be distributed to subscriber.Message management person is not the case where knowing subscriber Under be able to carry out management, improve the treatment effeciency of link barrage, make user's unaware and then improve user experience.
Since the electronic equipment that the present embodiment is introduced is equipment used by mobile terminal in the implementation embodiment of the present invention, So the electronics that those skilled in the art can understand the present embodiment is set based on method described in the embodiment of the present invention Standby specific embodiment and its various change form, so how to realize the embodiment of the present invention for the electronic equipment herein In method be no longer discussed in detail, as long as those skilled in the art implement the embodiment of the present invention in method used by set It is standby, belong to the range of the invention to be protected.
Referring to Fig. 4, Fig. 4 is a kind of embodiment signal of computer readable storage medium provided in an embodiment of the present invention Figure.
As shown in figure 4, present embodiments providing a kind of computer readable storage medium 400, it is stored thereon with computer journey Sequence 411, the computer program 411 realize following steps when being executed by processor: determining that the message subscribing person based on C Plus Plus takes out As interface;Determine the abstraction interface prevents object copies function;It generates message subscribing person and manages class, subscriber's management Class is for being managed subscriber;It is ordered by the interface of subscriber management class to interface offer subscriber is write Read interested message;Class is managed to the message subscribing person and carries out message parsing and by the message distribution being resolved to all Subscriber;Determine the subscriber of each message.
Optionally, in a kind of possible embodiment, it is specifically used for realizing when which is executed by processor Following steps: abstraction interface class MessageObserver, the class MessageObserver of message subscribing person is defined;Definition Destructor function virtual~MessageObserver () of the abstraction interface class;Define abstraction interface GetObserverMessageType;Define abstraction interface OnRecvPackMsg.
Optionally, in a kind of possible embodiment, it is specifically used for realizing when which is executed by processor Following steps: copy-constructor function is defined as the existing function private:void operator=(const of empty real MessageObserver&);The copy-constructor function is defined as the existing function MessageObserver of privately owned empty real (const MessageObserver&)。
Optionally, in a kind of possible embodiment, it is specifically used for realizing when which is executed by processor Following steps: a message management person class class ObserverManager is defined;Generate std::multimap < std:: String, MessageObserver* > map_push_observer, and by function multimap to the subscriber of message into Row management;The object map_push_observer of the function multimap is generated to store the subscriber.
Optionally, in a kind of possible embodiment, it is specifically used for realizing when which is executed by processor Following steps:
It is mentioned by interface void SetMessageTypeObserver (MessageObserver*_taskObserver) Supply all subscribers registered in all subscriber's dealing message management objects;Pass through abstraction interface GetObserverMessageType obtains all type of messages that subscriber needs to subscribe to;Obtain return value _ cmdtypes, institute State return value store subscription in need type of message;Define an iterator objects std::set < std::string >::iterator itr;It initializes iterator itr=_cmdtypes.begin ();It is each to traverse to obtain to write for circulation A type of message;The insert interface of multimap container is called to be inserted into subscriber into container.
Optionally, in a kind of possible embodiment, it is specifically used for realizing when which is executed by processor Following steps: one message parser pDecoder of creation;By message storage into the buf in mq.read (buf, len);It is logical It crosses and calls the message parser to parse the type type that the buf obtains message;An interface function is created to come to described Message is distributed to corresponding subscriber.
The embodiment of the present invention determines message subscribing person's abstraction interface MessageObserver based on C Plus Plus;It determines The abstraction interface prevents object copies function;It generates message subscribing person and manages class ObserverManager;It is ordered by described The interface that reader manages class ObserverManager carries out subscribing to interested message to interface offer subscriber is write;It is right The message subscribing person manages class and carries out message parsing and by the message distribution being resolved to all subscribers;Determine each The subscriber of message.The embodiment of the present invention then disappears to all by the classification to type of message, then by message managing module Breath subscriber is managed, after receiving message, to be distributed to subscriber.Message management person is not the case where knowing subscriber Under be able to carry out management, improve the treatment effeciency of link barrage, make user's unaware and then improve user experience.
It should be understood by those skilled in the art that, the embodiment of the present invention can provide as method, system or computer program Product.Therefore, complete hardware embodiment, complete software embodiment or reality combining software and hardware aspects can be used in the present invention Apply the form of example.Moreover, it wherein includes the computer of computer usable program code that the present invention, which can be used in one or more, The computer program implemented in usable storage medium (including but not limited to magnetic disk storage, CD-ROM, optical memory etc.) produces The form of product.

Claims (10)

1. a kind of method for linking barrage characterized by comprising
Determine message subscribing person's abstraction interface based on C Plus Plus;
Determine the abstraction interface prevents object copies function;
It generates message subscribing person and manages class, the subscriber manages class for being managed to subscriber;
It carries out subscribing to interested message to interface offer subscriber is write by the interface of subscriber management class;
Class is managed to the message subscribing person and carries out message parsing and by the message distribution being resolved to all subscribers;
Determine the subscriber of each message.
2. the method according to claim 1, wherein message subscribing person of the determination based on C Plus Plus is abstract Interface includes:
Define abstraction interface class MessageObserver, the class MessageObserver of message subscribing person;
Define destructor function virtual~MessageObserver () of the abstraction interface class;
Define abstraction interface GetObserverMessageType;
Define abstraction interface OnRecvPackMsg.
3. the method according to claim 1, wherein the determination abstraction interface prevents object copies function Can include:
Copy-constructor function is defined as the existing function private:void operator=(const of empty real MessageObserver&);
The copy-constructor function is defined as the existing function MessageObserver (const of privately owned empty real MessageObserver&)。
4. the method according to claim 1, wherein the generation message subscribing person manages class, the subscriber Management class is used to be managed subscriber
Define a message management person class class ObserverManager;
Std::multimap<std::string, MessageObserver*>map_push_observer are generated, and passes through letter Number multimap is managed the subscriber of message;
The object map_push_observer of the function multimap is generated to store the subscriber.
5. the method according to claim 1, wherein described manage the interface of class to writing by the subscriber Interface provides subscriber subscribe to interested message
It is supplied to by interface void SetMessageTypeObserver (MessageObserver*_taskObserver) All subscribers registered in all subscriber's dealing message management objects;
All type of messages that subscriber needs to subscribe to are obtained by abstraction interface GetObserverMessageType;
Obtain return value _ cmdtypes, the return value store subscription in need type of message;
Define an iterator objects std::set<std::string>:: iterator itr;
It initializes iterator itr=_cmdtypes.begin ();
For circulation is write to traverse to obtain each type of message;
The insert interface of multimap container is called to be inserted into the subscriber into container.
6. any method in -5 according to claim 1, which is characterized in that it is described to the message subscribing person manage class into Row message parses and includes: to all subscribers by the message distribution being resolved to
Create a message parser pDecoder;
By message storage into the buf in mq.read (buf, len);
The type type that the buf obtains message is parsed by calling the message parser;
An interface function is created to be distributed the message to corresponding subscriber.
7. according to the method described in claim 6, it is characterized in that, the creation one interface is distributed the message Include: to corresponding subscriber
Subscriber's number n of the message is obtained by the count function of multimap container;
Define iterator a std::multimap<std::string, MessageObserver*>:: itrator itr;
Find function is called to search corresponding subscriber from iterator;
After finding by subscriber storage into iterator itr;
It is recycled by for and the message is distributed to each subscriber one by one.
8. a kind of mobile terminal characterized by comprising
First determination unit, for determining message subscribing person's abstraction interface based on C Plus Plus;
Second determination unit prevents object copies function for determine the abstraction interface;
Generation unit, for generating message subscribing, person manages class, and the subscriber manages class for being managed to subscriber;
Subscriber units, the interface for managing class by the subscriber are emerging to carry out subscription sense to interface offer subscriber is write The message of interest;
Parse Dispatching Unit, for the message subscribing person manage class carry out message parsing and by the message distribution being resolved to All subscribers;
Third determination unit, for determining the subscriber of each message.
9. a kind of computer readable storage medium, including instruction, when run on a computer, so that computer is executed as weighed Benefit requires method described in 1-7 any one.
10. a kind of computer program product comprising instruction, when run on a computer, so that computer executes such as right It is required that method described in 1-7 any one.
CN201811067826.4A 2018-09-13 2018-09-13 A kind of method and mobile terminal linking barrage Pending CN109308202A (en)

Priority Applications (1)

Application Number Priority Date Filing Date Title
CN201811067826.4A CN109308202A (en) 2018-09-13 2018-09-13 A kind of method and mobile terminal linking barrage

Applications Claiming Priority (1)

Application Number Priority Date Filing Date Title
CN201811067826.4A CN109308202A (en) 2018-09-13 2018-09-13 A kind of method and mobile terminal linking barrage

Publications (1)

Publication Number Publication Date
CN109308202A true CN109308202A (en) 2019-02-05

Family

ID=65224516

Family Applications (1)

Application Number Title Priority Date Filing Date
CN201811067826.4A Pending CN109308202A (en) 2018-09-13 2018-09-13 A kind of method and mobile terminal linking barrage

Country Status (1)

Country Link
CN (1) CN109308202A (en)

Cited By (1)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
CN115495242A (en) * 2022-09-26 2022-12-20 佳源科技股份有限公司 Transformer area intelligent terminal APP communication processing method based on STL combined container

Citations (6)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
CN105357286A (en) * 2015-10-20 2016-02-24 中国电子科技集团公司第二十八研究所 Web-based real-time directional message pushing method
CN105959383A (en) * 2016-06-07 2016-09-21 北京百度网讯科技有限公司 Content subscription method and device
CN106131706A (en) * 2016-06-27 2016-11-16 武汉斗鱼网络科技有限公司 About the dynamic information push method of main broadcaster and device in a kind of mobile client application program
CN106250246A (en) * 2016-07-25 2016-12-21 福建天泉教育科技有限公司 A kind of method and system of event transmission
CN106648816A (en) * 2016-12-09 2017-05-10 武汉斗鱼网络科技有限公司 Multithread processing system and multithread processing method
CN108228625A (en) * 2016-12-15 2018-06-29 腾讯科技(深圳)有限公司 A kind of PUSH message processing method and processing device

Patent Citations (6)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
CN105357286A (en) * 2015-10-20 2016-02-24 中国电子科技集团公司第二十八研究所 Web-based real-time directional message pushing method
CN105959383A (en) * 2016-06-07 2016-09-21 北京百度网讯科技有限公司 Content subscription method and device
CN106131706A (en) * 2016-06-27 2016-11-16 武汉斗鱼网络科技有限公司 About the dynamic information push method of main broadcaster and device in a kind of mobile client application program
CN106250246A (en) * 2016-07-25 2016-12-21 福建天泉教育科技有限公司 A kind of method and system of event transmission
CN106648816A (en) * 2016-12-09 2017-05-10 武汉斗鱼网络科技有限公司 Multithread processing system and multithread processing method
CN108228625A (en) * 2016-12-15 2018-06-29 腾讯科技(深圳)有限公司 A kind of PUSH message processing method and processing device

Non-Patent Citations (1)

* Cited by examiner, † Cited by third party
Title
张俊: "《C++面向对象程序设计 第2版》", 31 August 2012, 中国铁道出版社 *

Cited By (1)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
CN115495242A (en) * 2022-09-26 2022-12-20 佳源科技股份有限公司 Transformer area intelligent terminal APP communication processing method based on STL combined container

Similar Documents

Publication Publication Date Title
US11411897B2 (en) Communication method and communication apparatus for message queue telemetry transport
US8001254B1 (en) Translating switch and method
US6182119B1 (en) Dynamically configurable filtered dispatch notification system
CN103188245B (en) A kind of fight game server system
CN105721318B (en) The method and apparatus of network topology are found in a kind of software defined network SDN
US7885204B1 (en) Method and system for testing network topology
CN102025567A (en) Sharing access detection method and related device
CN102130838A (en) Method for realizing peer-to-peer network caching system based on Ares protocol
CN109379638A (en) A kind of method and mobile terminal linking barrage
US10536397B2 (en) Packet count-based object locking protocol
CN109308202A (en) A kind of method and mobile terminal linking barrage
EP1917580B1 (en) Peer-to-peer communication system
CN109275014A (en) A kind of method and mobile terminal linking barrage
CN110896493B (en) Bullet screen linking method and mobile terminal
CN104969533B (en) A kind of data package processing method and device
CN110896570B (en) Bullet screen linking method and mobile terminal
Cisco FlowCollector Configuration and Control Format
Cisco FlowCollector Configuration and Control Protocol
Cisco FlowCollector Configuration and Control Protocol
KR100639568B1 (en) An apparatus for a performance test of information security system using network processor and a method thereof
CN100558114C (en) A kind of network application information processing system and method
CN108123868A (en) Communication system, method, apparatus and service terminal
WO2023207278A1 (en) Message processing method and apparatus
WO2023082706A1 (en) System and method for processing message, and network apparatus
Yue Research onC/SProtocol and P2PProtocol in Wireless Communication

Legal Events

Date Code Title Description
PB01 Publication
PB01 Publication
SE01 Entry into force of request for substantive examination
SE01 Entry into force of request for substantive examination
RJ01 Rejection of invention patent application after publication

Application publication date: 20190205

RJ01 Rejection of invention patent application after publication