CN109275014A - 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
CN109275014A
CN109275014A CN201811067415.5A CN201811067415A CN109275014A CN 109275014 A CN109275014 A CN 109275014A CN 201811067415 A CN201811067415 A CN 201811067415A CN 109275014 A CN109275014 A CN 109275014A
Authority
CN
China
Prior art keywords
port
barrage
data
barrage server
network
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.)
Granted
Application number
CN201811067415.5A
Other languages
Chinese (zh)
Other versions
CN109275014B (en
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 CN201811067415.5A priority Critical patent/CN109275014B/en
Publication of CN109275014A publication Critical patent/CN109275014A/en
Application granted granted Critical
Publication of CN109275014B publication Critical patent/CN109275014B/en
Active legal-status Critical Current
Anticipated expiration legal-status Critical

Links

Classifications

    • 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/442Monitoring of processes or resources, e.g. detecting the failure of a recording device, monitoring the downstream bandwidth, the number of times a movie has been viewed, the storage space available from the internal hard disk
    • H04N21/44227Monitoring of local network, e.g. connection or bandwidth variations; Detecting new devices in the local network
    • 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/431Generation of visual interfaces for content selection or interaction; Content or additional data rendering
    • H04N21/4312Generation of visual interfaces for content selection or interaction; Content or additional data rendering involving specific graphical features, e.g. screen layout, special fonts or colors, blinking icons, highlights or animations
    • H04N21/4314Generation of visual interfaces for content selection or interaction; Content or additional data rendering involving specific graphical features, e.g. screen layout, special fonts or colors, blinking icons, highlights or animations for fitting data in a restricted space on the screen, e.g. EPG data in a rectangular grid
    • 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/478Supplemental services, e.g. displaying phone caller identification, shopping application
    • H04N21/4788Supplemental services, e.g. displaying phone caller identification, shopping application communicating with other users, e.g. chatting
    • 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)
  • Multimedia (AREA)
  • Signal Processing (AREA)
  • Computer Networks & Wireless Communication (AREA)
  • Databases & Information Systems (AREA)
  • General Engineering & Computer Science (AREA)
  • Data Exchanges In Wide-Area Networks (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 includes: to define the data structure of IP and port, includes IP data and port data in the data structure;Barrage server domain name is determined according to the IP data and the port data;The balanced IP of the barrage server load is supported in selection;IP is parsed according to the barrage server domain name, the IP is converted to by the barrage server domain name;A container object is generated, the container object is for storing the multiple IP got;The multiple IP got are carried out at random and upset;Barrage server is linked according to the random IP with after upsetting.

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: defines the number of IP and port It include IP data and port data in the data structure according to structure;Bullet is determined according to the IP data and the port data Curtain server domain name;The balanced IP of the barrage server load is supported in selection;It is parsed according to the barrage server domain name IP, the IP are converted to by the barrage server domain name;A container object is generated, the container object is obtained for storing The multiple IP got;The multiple IP got are carried out at random and upset;Barrage is linked according to the random IP with after upsetting Server.
In a kind of possible embodiment, described to parse IP according to the barrage server domain name, the IP is by the bullet It includes: defined variable struct addrinfo structure that curtain server domain name, which is converted to,;Call function getaddrinfo by institute It states barrage server domain name and is converted into IP;The IP that will convert into is stored into the struct addrinfo structure;Described it will turn The IP that the IP and barrage server changed into is issued is upset at random together.
In a kind of possible embodiment, the defined variable struct addrinfo structure includes: by variable hints It empties, obtains memset (&hints, 0, sizeof (hints));The hints is assigned a value of SOCK_STREAM, is obtained Hints.ai_socktype=SOCK_STREAM.
In a kind of possible embodiment, the calling function getaddrinfo converts the barrage server domain name Include: calling system function getaddrinfo at IP, obtains getaddrinfo (host_name, NULL , &hints, & Result), wherein the host_name is barrage server domain name, and the result is for storing the IP being converted into.
In a kind of possible embodiment, one container object of the generation, the container object is got for storing Multiple IP include: generate an item, and to the item carry out assignment, obtain item.ip=ip;Item.port= port;vecip.push_back(item);The push_back function of container is called then to arrive ip storage in container, in container Include 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);, the ip is address family, and the port is port numbers.
In a kind of possible embodiment, it is described by interface random_shuffle come to the multiple IP got It carries out at random and after upsetting, which comprises select 3 IP as one group of link candidate site;Judge one group of chain The port numbers for waiting each IP in address are connect with the presence or absence of identical port numbers;Identical port numbers if it exists, then by identical end The corresponding IP of slogan is substituted for the different IP of port numbers.
In a kind of possible embodiment, the basis includes: at random creation with the IP link barrage server after upsetting Web socket socket;Call function int sockfd=socket (AF_INET, SOCK_STREAM, 0) foundation and barrage The connection of server;Address family and port numbers are set, function servaddr.sin_family=vecip [0] .ip, function are obtained Servaddr.sin_port=htons (vecip [0] .port);According to the successively chain of the IP in one group of link candidate site Barrage server is connect, until linking successfully and obtaining function int nRet=connect (sockfd, (struct sockaddr*)&servaddr,sizeof(servaddr))。
The second aspect of the embodiment of the present invention provides a kind of mobile terminal, comprising: definition unit, for defining IP and end Mouthful data structure, include IP data and port data in the data structure;Determination unit, for according to the IP data and The port data determines barrage server domain name;Selecting unit, for selecting to support the equilibrium of the barrage server load IP;Resolution unit, for parsing IP according to the barrage server domain name, the IP is converted by the barrage server domain name It obtains;Generation unit, for generating a container object, the container object is used to store the multiple IP got;At random Upset unit, for the multiple IP got to be carried out at random and upset;Link unit, for according at random and after upsetting IP link barrage server.
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.
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, the flow chart of the method for link barrage provided in an embodiment of the present invention, specifically includes:
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.
101, the data structure of IP and port are defined, includes IP data and port data in data structure.
Assuming that existing IP is listed as follows: ip1:119.23.45.6 port:4002 ip2:118.34.32.7 port: 4002ip3:120.45.33.1 port:4008 ip4:121.55.23.8 port:2009 ip5:130.55.23.8 port: 4009;The present embodiment defines the structure of an ip and port, strcunt ipportitem { string ip;int port;} It include ip data and port data in structure, then each ip and port can be stored by this ipportitem.
102, barrage server domain name is determined according to IP data and port data.
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.
103, the balanced IP of barrage server load is supported in selection.
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.
104, IP is parsed according to barrage server domain name.
Client needs to parse barrage server domain name first, parses more IP address.Then by domain name The IP that the IP and server of parsing are issued is upset at random together, and system provides getaddrinfo function and turns domain name Change IP address into.The present embodiment can realize the conversion of domain name then with calling system function.For the result of domain name transfer function It can then store 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 assignment is carried out to hints information, the present embodiment is to obtain the corresponding ip of domain name, so by socktype assignment For SOCK_STREAM.Following calling system function getaddrinfo realizes the parsing of domain name.getaddrinfo(host_ name,NULL,&hints,&result);Wherein needing incoming parameter host_name is then domain name, in corresponding the present embodiment After the completion of danmu.dy.com function call, as a result can then it store in hints and result;And a domain name parses Multiple ip, then storage is into result in the form of chained list.Next for circulation is write to traverse the ip parsed column Table.For (single=result;single;Single=single- > ai_next) { result is stored in result, next Then in ai_next structure, the present embodiment is obtained a result by traversing.Const char ip=single- > ai_ addr.ip;In each list structure, data are stored in this attribute of ip.
105, a container object is generated, container object is for storing 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 being also required to 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);ipportitemitem3; 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);All ip and port are all stored to this and arrived in vecip container.
106, the multiple IP got are carried out random and upset.
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.
107, 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 crossed the link for opening third ip without returning in 4 seconds;Int sockfd2=socket (AF_ INET, SOCK_STREAM, 0) it establishes and the connection of server;Create address family, servaddr2.sin_family=vecip [2].ip;It creates port numbers (host byte sequence to network bytes sequence), servaddr2.sin_port=htons (vecip [2] .port);The present embodiment opens the link of 3 groups of ip so in 12 seconds, int nRet=connect (sockfd1, (struct sockaddr*)&servaddr2,sizeof(servaddr2));If there is the link of any one ip returns, The present embodiment can all disconnect the link of other ip.To also 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.
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 that IP is parsed according to the barrage server domain name, call function getaddrinfo by the barrage It includes: defined variable struct addrinfo structure that server domain name, which is converted into IP,;Call function getaddrinfo described Barrage server domain name is converted into IP;The IP that will convert into is stored into the struct addrinfo structure;By the conversion At the IP that issues of IP and barrage server upset at random together.
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 defined variable struct addrinfo structure includes: to empty variable hints, obtains memset (&hints,0,sizeof(hints));The hints is assigned a value of SOCK_STREAM, obtains hints.ai_socktype= SOCK_STREAM。
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 calling function getaddrinfo by the barrage server domain name be converted into IP include: call system Unite function getaddrinfo, obtains getaddrinfo (host_name, NULL , &hints , &result), wherein described Host_name is barrage server domain name, and the result is for storing the IP being converted into.
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 container object vector<ipportitem>vecip of the generation come store get it is multiple IP includes: to generate an item, and carry out assignment to the item, obtains item.ip=ip;Item.port=port; vecip.push_back(item);It calls the push_back function of container then to arrive ip storage in container, includes in container 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);}.
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 that multiple IP for getting are carried out at random and upset by interface random_shuffle Later, which comprises select 3 IP as one group of link candidate site;It is each in address to judge that one group of link is waited The port numbers of IP whether there is identical port numbers;Identical port numbers if it exists then replace the corresponding IP of identical port numbers Change the different IP of port numbers into.
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, IP link barrage server of the basis at random and after upsetting includes: creation web socket socket;Function int sockfd=socket (AF_INET, SOCK_STREAM, 0) is called to establish the company with barrage server It connects;Address family and port numbers are set, function servaddr.sin_family=vecip [0] .ip, function are obtained Servaddr.sin_port=htons (vecip [0] .port);According to the successively chain of the IP in one group of link candidate site Barrage server is connect, until linking successfully and obtaining function int nRet=connect (sockfd, (struct sockaddr*)&servaddr,sizeof(servaddr))。
Embodiment two
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 client-side program, specific embodiment is as follows:
Step 1, the related data for creating socket, and linked with barrage server.
Mobile terminal creates the related data of socket Socket, and is linked with barrage server.Wherein, dependency number According to including 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, and the SocketBreaker is for triggering in socket Disconnected current link.Specifically, mobile terminal defines an object function SocketBreaker pipe, the object function SocketBreaker pipe is used for its termination current link of socket link triggering.
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 the OnError function of event object Event, and parameter is set as ConnectTimeoutErr indicates link time-out error;Function event.OnError (ConnectingErr), if returned Value selectRet < 0, then it represents that link error calls function event.OnError (ConnectingErr) notice upper layer current Socket error.Otherwise explanation this time link is successfully, then to continue subsequent network and give out a contract for a project and packet receiving operation;Function Event.OnConnect (), for calling the OnConnect of event object event to inform that upper layer current link is successful.
Step 5, the thread object Thread for creating socket and the execution function void__RunThread for executing 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 (0==selectRet) { indicates then directly to return currently without readable data without writeable data, and without exception It returns and waits next state, continue;}
If (0 > selectRet) { is indicated that current socket produces exception, is then informed using event object event Layer has currently gone out first IO read-write error, 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.
Socket is judged by select object whether in reading set Read_FD_ISSET, to know current Whether socket can read data;Inform that the current socket in upper layer there are data by calling the OnRead of event object at this time It can read, so as to read the network data of barrage server, 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: { wherein, interface return value is bool GetRetryFlag (int nStauts) Bool variable wants reconnection for true expression, indicates not reconnection for false;Interface name is GetRetryFlag;Wherein, only There is a 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, query result 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 return As a result.
There is status code query interface, then it 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 () // a static container object is defined 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;
It is as follows for the operation of not reconnection: enum NotRetryCode kTick=500 indicates that error code is 500, by Multiple equipment is logged in its same account while logging in the same direct broadcasting room, and barrage server can kick a client off.This Shi Ze not can be carried out reconnection.KClientDisconnect=501 indicates that error code is 501, indicates that client actively closes Current link, therefore do 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.
{ explanation is not found in reconnection error code if (itr==mapRetry.end ());It is following then need to look into Look for the error code for not needing reconnection;
Itr=mapNotRetry.find (errorcode);
If (itr==mapNotRetry.end ()) is not { if find explanation also not in the error code for not needing reconnection In, then illustrating that these error codes needs are further handled;
{ wherein error code 800 indicates room number mistake to if (errorcode==800), and client then can be from complete at this time Information centre of office obtains room information.
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.Progress after obtaining again Reconnection;
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, obtains token Afterwards, then carry out reconnection again.
}
{ 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, The design link solution of network data distribution based on type of message, specific embodiment are as follows:
Step 1 determines message subscribing person's abstraction interface MessageObserver based on C Plus Plus.
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.
Step 2, determine abstraction interface prevent 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.
Step 3 generates message subscribing person management class ObserverManager.
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。
Step 4, the interface that class ObserverManager is managed by subscriber are carried out to interface offer subscriber is write Subscribe to interested message.
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.
Step 5 manages message subscriber class progress message parsing and by the message distribution being resolved to all subscription Person.
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, call managing message distribution class then to be distributed to 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.
Step 6, the subscriber for determining each message.
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 () { defines a static state first Container object types;
static std::set<std::string>types;If the lower types of judgement has been stored, institute is in need to be ordered The message read then directly returns;
if(!types.empty()){
return types;
Otherwise without the message of deposit subscription.
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.
}
So far complete herein barrage message subscribing person total interface realization, and barrage content is shown Show.
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.
Embodiment seven
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.Be implemented as follows: the address information for defining a socket becomes Measure struct sockaddr_in addr;Addr.sin_len=sizeof (sockaddr_in), addr.sin_family= Then AF_INET6 carries out assignment to it wherein being this time shown to be using IPV6, wherein port numbers use 80 ports, then IP It 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 net Network, and it is assigned a value of 1;Defining kWIFI indicates that current network is WIFI, then automatic assignment is 2;Defining k4G indicates 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) is { if current Link is not WIFI, then continues to judge that its type is ConnectivityManager.TYPE_MOBILE, if so, Show current link is the 4G network of mobile phone.
CurStatus=k4G;
Else can be used currently without network, then be in network off-state.
CurStatus=kNONET;
}
}
}
}
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.
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) is { if current Link is not WIFI, then continues to judge that its type is ConnectivityManager.TYPE_MOBILE, if so, Show current link is the 4G network of mobile phone.
CurStatus=k4G;
Else can be used currently without network, then be in network off-state.
CurStatus=kNONET;
}
}
}
}
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.
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:
Definition unit 201 includes IP data and port in the data structure for defining the data structure of IP and port Data;Determination unit 202, for determining barrage server domain name according to the IP data and the port data;Selecting unit 203, the IP of the equilibrium for selecting to support the barrage server load;Resolution unit 204, for according to the barrage service Device domain name mapping IP, the IP are converted to by the barrage server domain name;Generation unit 205, for generating a container Object, the container object is for storing the multiple IP got;Upset unit 206 at random, for it is described get it is more A IP is carried out at random and is upset;Link unit 207, for linking barrage server according to the random IP with after upsetting.
Optionally, in some possible implementations, resolution unit 204 is specifically used for: defined variable struct Addrinfo structure;Call function getaddrinfo that the barrage server domain name is converted into IP;The IP storage that will convert into Into the struct addrinfo structure;The IP that the IP being converted into and barrage server are issued is carried out at random together Upset.
Optionally, in some possible implementations, resolution unit 204 is specifically used for: variable hints being emptied, is obtained To memset (&hints, 0, sizeof (hints));The hints is assigned a value of SOCK_STREAM, obtains hints.ai_ Socktype=SOCK_STREAM.
Optionally, in some possible implementations, resolution unit 204 is specifically used for: calling system function Getaddrinfo obtains getaddrinfo (host_name, NULL , &hints , &result), wherein the host_name For barrage server domain name, the result is for storing the IP being converted into.
Optionally, in some possible implementations, generation unit 205 is specifically used for: generating an item, and to institute It states item and carries out assignment, obtain item.ip=ip;Item.port=port;vecip.push_back(item);Call container Push_back function then by ip storage arrived in container, in container include 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);, the ip is address family, and the port is port numbers.
Optionally, in some possible implementations, mobile terminal further include: module of selection 208, for selecting 3 IP is as one group of link candidate site;Judging unit 209, for judging that the port numbers of each IP in address are waited in one group of link With the presence or absence of identical port numbers;Replacement unit 210, identical port numbers, then be used for identical port numbers are corresponding if it exists IP be substituted for the different IP of port numbers.
Optionally, in some possible implementations, link unit 207 is specifically used for: creation web socket socket;Function int sockfd=socket (AF_INET, SOCK_STREAM, 0) is called to establish the company with barrage server It connects;Address family and port numbers are set, function servaddr.sin_family=vecip [0] .ip, function are obtained Servaddr.sin_port=htons (vecip [0] .port);According to the successively chain of the IP in one group of link candidate site Barrage server is connect, until linking successfully and obtaining function int nRet=connect (sockfd, (struct sockaddr*)&servaddr,sizeof(servaddr))。
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 The data structure for defining IP and port is performed the steps of when 311, includes IP data and port data in the data structure; Barrage server domain name is determined according to the IP data and the port data;The equal of the barrage server load is supported in selection The IP of weighing apparatus;IP is parsed according to the barrage server domain name, the IP is converted to by the barrage server domain name;Generate one A container object, the container object is for storing the multiple IP got;To multiple IP for getting carry out at random and Upset;Barrage server is linked according to the random IP with after upsetting.
Optionally, in a kind of possible embodiment, the processor is specifically used for: defined variable struct Addrinfo structure;Call function getaddrinfo that the barrage server domain name is converted into IP;The IP storage that will convert into Into the struct addrinfo structure;The IP that the IP being converted into and barrage server are issued is carried out at random together Upset.
Optionally, in a kind of possible embodiment, the processor is specifically used for: variable hints being emptied, is obtained memset(&hints,0,sizeof(hints));The hints is assigned a value of SOCK_STREAM, obtains hints.ai_ Socktype=SOCK_STREAM.
Optionally, in a kind of possible embodiment, the processor is specifically used for: calling system function Getaddrinfo obtains getaddrinfo (host_name, NULL , &hints , &result), wherein the host_name For barrage server domain name, the result is for storing the IP being converted into.
Optionally, in a kind of possible embodiment, the processor is specifically used for: generating an item, and to described Item carries out assignment, obtains item.ip=ip;Item.port=port;vecip.push_back(item);Call container Push_back function has then arrived ip storage in container, includes ipportitem item1 in container;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);, the ip is address family, and the port is port numbers.
Optionally, in a kind of possible embodiment, the processor is specifically used for: selecting 3 IP as one group of link Candidate site;Judge that one group of link waits the port numbers of each IP in address with the presence or absence of identical port numbers;Phase if it exists Same port numbers, then be substituted for the different IP of port numbers for the corresponding IP of identical port numbers.
Optionally, in a kind of possible embodiment, the processor is specifically used for: creation web socket socket; Function int sockfd=socket (AF_INET, SOCK_STREAM, 0) is called to establish the connection with barrage server;Setting Address family and port numbers obtain function servaddr.sin_family=vecip [0] .ip, function servaddr.sin_port =htons (vecip [0] .port);Barrage server is successively linked according to the IP in one group of link candidate site, until It links successfully and obtains function int nRet=connect (sockfd, (struct sockaddr*), sizeof (servaddr))。
In the specific implementation process, when processor 320 executes computer program 311, the corresponding embodiment of Fig. 1 may be implemented Middle any embodiment.
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: defining the data structure of IP and port, the number According in structure include IP data and port data;Barrage server domain name is determined according to the IP data and the port data; The balanced IP of the barrage server load is supported in selection;IP is parsed according to the barrage server domain name, the IP is by institute Barrage server domain name is stated to be converted to;A container object is generated, the container object is for storing the multiple IP got; The multiple IP got are carried out at random and upset;Barrage server is linked according to the random IP with after upsetting.
Optionally, in a kind of possible embodiment, it is specifically used for realizing when which is executed by processor Following steps: defined variable struct addrinfo structure;Call function getaddrinfo by the barrage server domain name It is converted into IP;The IP that will convert into is stored into the struct addrinfo structure;The IP being converted into and barrage are taken The IP that business device issues is upset at random together.
Optionally, in a kind of possible embodiment, it is specifically used for realizing when which is executed by processor Following steps: variable hints is emptied, and obtains memset (&hints, 0, sizeof (hints));The hints is assigned a value of SOCK_STREAM obtains hints.ai_socktype=SOCK_STREAM.
Optionally, in a kind of possible embodiment, it is specifically used for realizing when which is executed by processor Following steps: calling system function getaddrinfo obtains getaddrinfo (host_name, NULL , &hints, & Result), wherein the host_name is barrage server domain name, and the result is for storing the IP being converted into.
Optionally, in a kind of possible embodiment, it is specifically used for realizing when which is executed by processor Following steps: an item is generated, and assignment is carried out to the item, obtains item.ip=ip;Item.port=port; vecip.push_back(item);It calls the push_back function of container then to arrive ip storage in container, includes in container 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);, the ip is address family, and the port is port numbers.
Optionally, in a kind of possible embodiment, it is specifically used for realizing when which is executed by processor Following steps: 3 IP are selected as one group of link candidate site;Judge that the port numbers of each IP in address are waited in one group of link With the presence or absence of identical port numbers;The corresponding IP of identical port numbers is then substituted for port numbers by identical port numbers if it exists Different IP.
Optionally, in a kind of possible embodiment, it is specifically used for realizing when which is executed by processor Following steps: function int sockfd=socket (AF_INET, SOCK_STREAM, 0) is called to establish and barrage server Connection;Address family and port numbers are set, function servaddr.sin_family=vecip [0] .ip, function are obtained Servaddr.sin_port=htons (vecip [0] .port);According to the successively chain of the IP in one group of link candidate site Barrage server is connect, until linking successfully and obtaining function int nRet=connect (sockfd, (struct sockaddr*)&servaddr,sizeof(servaddr))。
The embodiment of the present invention defines data structure the strcunt ipportitem, the strcunt of IP and port It include IP data and port data in ipportitem;Barrage server domain is determined according to the IP data and the port data Name;The balanced IP of the barrage server load is supported in selection;IP is parsed according to the barrage server domain name, calls function The barrage server domain name is converted into IP by getaddrinfo;Generate a container object vector<ipportitem> Vecip stores the multiple IP got;By interface random_shuffle come to multiple IP for getting carry out with Machine and upset;Barrage server is linked according to the random IP with after upsetting.The embodiment of the present invention, successively select 3 from container A IP carries out trial link, more faster than traditional approach connect barrage server,.The process of link barrage is carried out Optimization improves the treatment effeciency of link barrage.
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
The data structure of IP and port are defined, includes IP data and port data in the data structure;
Barrage server domain name is determined according to the IP data and the port data;
The balanced IP of the barrage server load is supported in selection;
IP is parsed according to the barrage server domain name, the IP is converted to by the barrage server domain name;
A container object is generated, the container object is for storing the multiple IP got;
The multiple IP got are carried out at random and upset;
Barrage server is linked according to the random IP with after upsetting.
2. the method according to claim 1, wherein described parse IP, institute according to the barrage server domain name It states IP and is converted to by the barrage server domain name and include:
Defined variable struct addrinfo structure;
Call function getaddrinfo that the barrage server domain name is converted into IP;
The IP that will convert into is stored into the struct addrinfo structure;
The IP that the IP being converted into and barrage server issue is upset at random together.
3. according to the method described in claim 2, it is characterized in that, the defined variable struct addrinfo structure includes:
Variable hints is emptied, memset (&hints, 0, sizeof (hints) are obtained);
The hints is assigned a value of SOCK_STREAM, obtains hints.ai_socktype=SOCK_STREAM.
4. according to the method described in claim 2, it is characterized in that, the calling function getaddrinfo takes the barrage Business device domain name is converted into IP and includes:
Calling system function getaddrinfo obtains getaddrinfo (host_name, NULL , &hints , &result), In, the host_name is barrage server domain name, and the result is for storing the IP being converted into.
5. the method according to claim 1, wherein one container object of the generation, the container object is used Include: in multiple IP that storage is got
An item is generated, and assignment is carried out to the item, obtains item.ip=ip;Item.port=port; vecip.push_back(item);
It calls the push_back function of container then to arrive ip storage in container, includes ipportitem item1 in container; 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);, the ip is address family, and the port is port numbers.
6. any method in -5 according to claim 1, which is characterized in that described to be carried out to the multiple IP got It is random and after upsetting, which comprises
3 IP are selected as one group of link candidate site;
Judge that one group of link waits the port numbers of each IP in address with the presence or absence of identical port numbers;
The corresponding IP of identical port numbers is then substituted for the different IP of port numbers by identical port numbers if it exists.
7. according to the method described in claim 6, it is characterized in that, the basis links barrage service with the IP after upsetting at random Device includes:
Create web socket socket;
Function int sockfd=socket (AF_INET, SOCK_STREAM, 0) is called to establish the connection with barrage server;
Address family and port numbers are set, function servaddr.sin_family=vecip [0] .ip, function are obtained Servaddr.sin_port=htons (vecip [0] .port);
Barrage server is successively linked according to the IP in one group of link candidate site, until linking successfully and obtaining function Int nRet=connect (sockfd, (struct sockaddr*) &servaddr, sizeof (servaddr)).
8. a kind of mobile terminal characterized by comprising
Definition unit includes IP data and port data in the data structure for defining the data structure of IP and port;
Determination unit, for determining barrage server domain name according to the IP data and the port data;
Selecting unit, the IP of the equilibrium for selecting to support the barrage server load;
Resolution unit, for parsing IP according to the barrage server domain name, the IP is converted by the barrage server domain name It obtains;
Generation unit, for generating a container object, the container object is for storing the multiple IP got;
Upset unit at random, for the multiple IP got to be carried out at random and upset;
Link unit, for linking barrage server according to the random IP with after upsetting.
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.
CN201811067415.5A 2018-09-13 2018-09-13 Bullet screen linking method and mobile terminal Active CN109275014B (en)

Priority Applications (1)

Application Number Priority Date Filing Date Title
CN201811067415.5A CN109275014B (en) 2018-09-13 2018-09-13 Bullet screen linking method and mobile terminal

Applications Claiming Priority (1)

Application Number Priority Date Filing Date Title
CN201811067415.5A CN109275014B (en) 2018-09-13 2018-09-13 Bullet screen linking method and mobile terminal

Publications (2)

Publication Number Publication Date
CN109275014A true CN109275014A (en) 2019-01-25
CN109275014B CN109275014B (en) 2021-09-07

Family

ID=65189335

Family Applications (1)

Application Number Title Priority Date Filing Date
CN201811067415.5A Active CN109275014B (en) 2018-09-13 2018-09-13 Bullet screen linking method and mobile terminal

Country Status (1)

Country Link
CN (1) CN109275014B (en)

Citations (11)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
CN102638580A (en) * 2012-03-30 2012-08-15 奇智软件(北京)有限公司 Webpage information processing method and webpage information processing device
CN102843445A (en) * 2012-09-29 2012-12-26 北京奇虎科技有限公司 Browser and domain name resolution method thereof
CN105373554A (en) * 2014-08-25 2016-03-02 北京爱声声科技有限公司 Mobile device webpage based screen popup method and system
CN106792225A (en) * 2016-11-09 2017-05-31 武汉斗鱼网络科技有限公司 front end barrage control method and device
WO2017101430A1 (en) * 2015-12-15 2017-06-22 乐视控股(北京)有限公司 Voice bullet screen generation method and apparatus
US20170272800A1 (en) * 2016-03-21 2017-09-21 Le Holdings (Beijing) Co., Ltd. Method for bullet screen pushing and electronic device
CN107396199A (en) * 2017-08-02 2017-11-24 武汉斗鱼网络科技有限公司 Barrage method for exhibiting data and device, computer-readable recording medium
CN108021604A (en) * 2017-10-24 2018-05-11 山东科技大学 A kind of web crawlers method for crawling barrage in Dou Yu webcast websites main broadcaster room
CN108156508A (en) * 2017-12-28 2018-06-12 北京安云世纪科技有限公司 Method, apparatus, mobile terminal, server and the system of barrage information processing
CN108366277A (en) * 2018-03-30 2018-08-03 武汉斗鱼网络科技有限公司 A kind of barrage server connection method, client and readable storage medium storing program for executing
US10284806B2 (en) * 2017-01-04 2019-05-07 International Business Machines Corporation Barrage message processing

Patent Citations (11)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
CN102638580A (en) * 2012-03-30 2012-08-15 奇智软件(北京)有限公司 Webpage information processing method and webpage information processing device
CN102843445A (en) * 2012-09-29 2012-12-26 北京奇虎科技有限公司 Browser and domain name resolution method thereof
CN105373554A (en) * 2014-08-25 2016-03-02 北京爱声声科技有限公司 Mobile device webpage based screen popup method and system
WO2017101430A1 (en) * 2015-12-15 2017-06-22 乐视控股(北京)有限公司 Voice bullet screen generation method and apparatus
US20170272800A1 (en) * 2016-03-21 2017-09-21 Le Holdings (Beijing) Co., Ltd. Method for bullet screen pushing and electronic device
CN106792225A (en) * 2016-11-09 2017-05-31 武汉斗鱼网络科技有限公司 front end barrage control method and device
US10284806B2 (en) * 2017-01-04 2019-05-07 International Business Machines Corporation Barrage message processing
CN107396199A (en) * 2017-08-02 2017-11-24 武汉斗鱼网络科技有限公司 Barrage method for exhibiting data and device, computer-readable recording medium
CN108021604A (en) * 2017-10-24 2018-05-11 山东科技大学 A kind of web crawlers method for crawling barrage in Dou Yu webcast websites main broadcaster room
CN108156508A (en) * 2017-12-28 2018-06-12 北京安云世纪科技有限公司 Method, apparatus, mobile terminal, server and the system of barrage information processing
CN108366277A (en) * 2018-03-30 2018-08-03 武汉斗鱼网络科技有限公司 A kind of barrage server connection method, client and readable storage medium storing program for executing

Non-Patent Citations (1)

* Cited by examiner, † Cited by third party
Title
CHRISTIAN HUITEMA著,陶文星,胡文才译: "《新因特网协议IPv6》", 31 December 2000 *

Also Published As

Publication number Publication date
CN109275014B (en) 2021-09-07

Similar Documents

Publication Publication Date Title
US11411897B2 (en) Communication method and communication apparatus for message queue telemetry transport
CN102104541B (en) Header processing engine
US8341218B2 (en) Technique for enabling a plurality of software components to communicate in a software component matrix environment
US20070038774A1 (en) Translating Switch and Method
EP2151095B1 (en) Method and apparatus for discovering universal plug and play device using resource information
CN102025567A (en) Sharing access detection method and related device
CN103188245A (en) Fight game server system
CN109379638A (en) A kind of method and mobile terminal linking barrage
EP2139193B1 (en) A method of performing data mediation, and an associated computer program product, data mediation device and information system
US6842781B1 (en) Download and processing of a network management application on a network device
EP1917580B1 (en) Peer-to-peer communication system
CN109308202A (en) A kind of method and mobile terminal linking barrage
CN117544592A (en) Domain name resolution method, device, node, electronic equipment and storage medium
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
US7260621B1 (en) Object-oriented network management interface
CN109379453B (en) Method and system for detecting IP address of DNS (Domain name Server) outlet server
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
Baeckstroem et al. Design of a contact service in a Jini-based spontaneous network
WO2023207278A1 (en) Message processing method and apparatus
EP4412310A1 (en) System and method for processing message, and network apparatus
Son et al. An intelligent SDP discovery scheme using knowledge-based adaptive probing

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
GR01 Patent grant
GR01 Patent grant