CN109379638A - 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
CN109379638A
CN109379638A CN201811067058.2A CN201811067058A CN109379638A CN 109379638 A CN109379638 A CN 109379638A CN 201811067058 A CN201811067058 A CN 201811067058A CN 109379638 A CN109379638 A CN 109379638A
Authority
CN
China
Prior art keywords
barrage
status code
reconnection
mapstatus
socket
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
CN201811067058.2A
Other languages
Chinese (zh)
Other versions
CN109379638B (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 CN201811067058.2A priority Critical patent/CN109379638B/en
Publication of CN109379638A publication Critical patent/CN109379638A/en
Application granted granted Critical
Publication of CN109379638B publication Critical patent/CN109379638B/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/47End-user applications
    • H04N21/488Data services, e.g. news ticker
    • H04N21/4884Data services, e.g. news ticker for displaying subtitles
    • HELECTRICITY
    • H04ELECTRIC COMMUNICATION TECHNIQUE
    • H04NPICTORIAL COMMUNICATION, e.g. TELEVISION
    • H04N21/00Selective content distribution, e.g. interactive television or video on demand [VOD]
    • H04N21/80Generation or processing of content or additional data by content creator independently of the distribution process; Content per se
    • H04N21/85Assembly of content; Generation of multimedia applications
    • H04N21/858Linking data to content, e.g. by linking an URL to a video object, by creating a hotspot
    • H04N21/8586Linking data to content, e.g. by linking an URL to a video object, by creating a hotspot by using a URL

Landscapes

  • Engineering & Computer Science (AREA)
  • Multimedia (AREA)
  • Signal Processing (AREA)
  • Mobile Radio Communication Systems (AREA)

Abstract

The invention discloses a kind of methods and mobile terminal for linking barrage, and when the unstable networks of mobile terminal are disconnected barrage, Auto-reconnect technology reconnection barrage is also can be used in mobile terminal, improve the efficiency of link barrage.The method of the present invention includes: the mapping table for generating storage state code;Determine that socket all possible state and status code during linking barrage, the status code and the possible state correspond;By status code storage into the mapping table;Judge whether barrage needs to carry out the inquiry of reconnection according to the status code;If status code needs to carry out barrage reconnection, barrage server is linked according to the status code.

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 a kind of methods and mobile terminal for linking barrage, for working as the network of mobile terminal 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.
The first aspect of the embodiment of the present invention provides a kind of method for linking barrage, comprising: generates storage state code Mapping table;Determine socket all possible state and status code during linking barrage, the status code and institute Possible state is stated to correspond;By status code storage into the mapping table;Judge that barrage is according to the status code The no inquiry for needing to carry out reconnection;If status code needs to carry out barrage reconnection, barrage server is linked according to the status code.
In a kind of possible embodiment, the mapping table for generating storage state code includes: to call Standard Template Library STL The map container of container;Define a map<int, bool>type object mapStatus, wherein the int is that the map holds The key value of device, for storing the status code of socket;The bool is for storing whether current state code needs to carry out reconnection.
In a kind of possible embodiment, all possible state in the determining entire link process of socket And status code, the status code and the possible state one-to-one correspondence include: the status code for generating socket, described Status code include kInitErr, kSocketThreadStart, kSocketThreadStartErr, kTcpConnectIpErr, KTcpConnectTimeoutErr, kTcpIOErr, kTcpDisConnectedbyRemote and kTcpDisConnected;Institute State kInitErr for indicate initialization error code;The kSocketThreadStart is for indicating that socket initializes line Journey;The kSocketThreadStartErr is for indicating socket initialization thread error code;It is described KTcpConnectIpErr generates error code when for indicating that socket links ip;The kTcpConnectTimeoutErr is used Time-out is generated in expression socket;The kTcpIOErr generates io error code for indicating that socket sends data;It is described KTcpDisConnectedbyRemote is for indicating that socket is linked by server closing;The kTcpDisConnected is used It is disconnected in indicating that socket is linked;Assignment is carried out to the status code, the value of each status code is different.
It is described that assignment, the value difference packet of each status code are carried out to the status code in a kind of possible embodiment It includes: calling enumerated variable type enum SocketStatus;Successively by kInitErr, kSocketThreadStart, kSocketThreadStartErr、kTcpConnectIpErr、kTcpConnectTimeoutErr、kTcpIOErr、 KTcpDisConnectedbyRemote and kTcpDisConnected is assigned a value of 1,2,3,4,5,6,7,8.
In a kind of possible embodiment, it is described by status code storage into the mapping table include: will need into The status code of row reconnection is assigned a value of true, and the status code for not needing to carry out reconnection is assigned a value of false.
It is described that the status code for carrying out reconnection will be needed to be assigned a value of true in a kind of possible embodiment, will not need into It includes: that mapStatus container is called to carry out assignment to status code that the status code of row reconnection, which is assigned a value of false, wherein MapStatus [kInitErr]=true, mapStatus [kSocketThreadStart]=false, mapStatus [kSocketThreadStartErr]=true, mapStatus [kTcpConnectIpErr]=true, mapStatus [kTcpConnectTimeoutErr]=true, mapStatus [kTcpIOErr]=true, mapStatus [kTcpDisConnectedbyRemote]=false, mapStatus [kTcpDisConnected]=true;It is described MapStatus [kInitErr]=true indicates that storage key value is kInitErr and needs to carry out barrage in mapStatus container Reconnection, the mapStatus [kSocketThreadStart]=false indicate that storage key value is in mapStatus container KSocketThreadStart and do not need carry out barrage reconnection, the mapStatus [kSocketThreadStartErr]= True indicates that storage key value is kSocketThreadStartErr and needs to carry out barrage reconnection in mapStatus container, described MapStatus [kTcpConnectIpErr]=true indicates that storage key value is in mapStatus container KTcpConnectIpErr and need to carry out barrage reconnection, mapStatus [the kTcpConnectTimeoutErr]=true Indicate that storage key value is kTcpConnectTimeoutErr and needs to carry out barrage reconnection in mapStatus container, it is described MapStatus [kTcpIOErr]=true indicates that storage key value is kTcpIOErr and needs to carry out bullet in mapStatus container Curtain reconnection, mapStatus [kTcpDisConnectedbyRemote]=false indicate to store key value in mapStatus container For [kTcpDisConnectedbyRemote and do not need carry out barrage reconnection, the mapStatus [kTcpDisConnected]=true indicate mapStatus container in storage key value be kTcpDisConnected and need into Row barrage reconnection.
In a kind of possible embodiment, the inquiry packet for being judged whether to need to carry out reconnection according to the status code Include: calling interface function bool GetRetryFlag (int nStauts) inquires the status code, wherein described GetRetryFlag is interface name, and the int nStauts indicates the status code of inquiry, and the bool is return value, described Return value is that reconnection barrage is wanted in true expression, and the return value is that false indicates not reconnection barrage;Call the find of map container Interface is inquired.
The second aspect of the embodiment of the present invention provides a kind of mobile terminal, comprising: generation unit, for generating storage shape The mapping table of state code;Certain unit, for determining socket all possible state and shape during linking barrage State code, the status code and the possible state correspond;Storage unit is reflected for storing the status code to described In firing table;Judging unit, for judging whether barrage needs to carry out the inquiry of reconnection according to the status code;Query unit, if Status code needs to carry out barrage reconnection, then for linking barrage server according to the status code.
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 a kind of methods and mobile terminal for linking barrage, for working as the network of mobile terminal not When stabilization is disconnected barrage, Auto-reconnect technology reconnection barrage is also can be used in mobile terminal, improves 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:
101, the mapping table of storage state code is generated.
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.
102, socket all possible state and status code during linking barrage, status code and institute are determined Possible state is stated to correspond.
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.
103, by status code storage 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.
104, judge whether barrage needs to carry out the inquiry of 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, The iterator of a map container is defined first, specifically realizes that function includes;map<int,bool>::iterator itr; Then its find interface is called to inquire current state code, query result is then stored in itr iterator, wherein iterator Value value is then end value, and specific implementation function includes: itr=mapStatus.find (nStauts);And by iterator Value value is used as and returns the result, i.e. retrun (* itr) .value };
If 105, status code needs to carry out barrage reconnection, barrage server is linked according to status code.
There is status code query interface, then can obtain whether current state needs reconnection barrage service by inquiring Device, to provide basic technical support 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.
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 generate storage state code mapping table include: call Standard Template Library STL container map container; Define a map<int, bool>type object mapStatus, wherein the int is the key value of the map container, is used for Store the status code of socket;The bool is for storing whether current state code needs to carry out reconnection.
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, all possible state and status code in the determining entire link process of socket are described It includes: the status code for generating socket that status code and the possible state, which correspond, and the status code includes kInitErr、kSocketThreadStart、kSocketThreadStartErr、kTcpConnectIpErr、 KTcpConnectTimeoutErr, kTcpIOErr, kTcpDisConnectedbyRemote and kTcpDisConnected;Institute State kInitErr for indicate initialization error code;The kSocketThreadStart is for indicating that socket initializes line Journey;The kSocketThreadStartErr is for indicating socket initialization thread error code;It is described KTcpConnectIpErr generates error code when for indicating that socket links ip;The kTcpConnectTimeoutErr is used Time-out is generated in expression socket;The kTcpIOErr generates io error code for indicating that socket sends data;It is described KTcpDisConnectedbyRemote is for indicating that socket is linked by server closing;The kTcpDisConnected is used It is disconnected in indicating that socket is linked;Assignment is carried out to the status code, the value of each status code is different.
Optionally, on the basis of above-mentioned Fig. 1 corresponding embodiment, the method for link barrage provided in an embodiment of the present invention Alternative embodiment in, it is described to the status code carry out assignment, the value difference of each status code includes: calling enumerated variable Type enum SocketStatus;Successively by kInitErr, kSocketThreadStart, kSocketThreadStartErr、kTcpConnectIpErr、kTcpConnectTimeoutErr、kTcpIOErr、 KTcpDisConnectedbyRemote and kTcpDisConnected is assigned a value of 1,2,3,4,5,6,7,8.
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, described by status code storage includes: that will need to carry out the status code of reconnection into the mapping table It is assigned a value of true, the status code for not needing to carry out reconnection is assigned a value of false.
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 the status code for carrying out reconnection will be needed to be assigned a value of true, will not need carry out reconnection status code Being assigned a value of false includes: that mapStatus container is called to carry out assignment to status code, wherein and mapStatus [kInitErr]= True, mapStatus [kSocketThreadStart]=false, mapStatus [kSocketThreadStartErr]= True, mapStatus [kTcpConnectIpErr]=true, mapStatus [kTcpConnectTimeoutErr]= True, mapStatus [kTcpIOErr]=true, mapStatus [kTcpDisConnectedbyRemote]=false, MapStatus [kTcpDisConnected]=true.
Optionally, on the basis of above-mentioned Fig. 1 corresponding embodiment, the method for link barrage provided in an embodiment of the present invention Alternative embodiment in, it is described to judge whether that needing the inquiry for carrying out reconnection includes: calling interface function according to the status code Bool GetRetryFlag (int nStauts) inquires the status code, wherein and the GetRetryFlag is interface name, The int nStauts indicates the status code of inquiry, and the bool is return value, and the return value is that reconnection bullet is wanted in true expression Curtain, the return value are that false indicates not reconnection barrage;The find interface of map container is called to be inquired.
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 event object Event's OnError function, and parameter is set as ConnectTimeoutErr, indicates link time-out error;Function Event.OnError (ConnectingErr), if return value selectRet < 0, then it represents that function is called in link error Event.OnError (ConnectingErr) notifies the current socket error in upper layer.Otherwise explanation this time link is successful, Then continue subsequent network to give out a contract for a project and packet receiving operation;Function event.OnConnect (), for calling event object event's OnConnect informs that upper layer current link is successful.
Step 5, 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.
The entire logic function of this while circulation is therefore the separate threads of socket in RunThread function logics This section of code logic can be executed.The while circulation of creation is transmitted across constantly to receive barrage server from socket The network data come, and the network data for constantly needing to send by client from socket sends a barrage server.
First look at the state of socket, while (true) { int selectRet=select.Select ();
Currently without readable data without writeable data, and without exception, then next state, if (0==are directly returned to waiting for selectRet){continue;}
Current socket produces exception, then it is wrong to inform that upper layer has currently gone out first IO read-write using event object event Accidentally, if (0 > selectRet) { event.OnError (IOErr);
Terminate previous cycle, return by return;, whether it, which has exception, next otherwise is checked to socket;
Socket is judged by select object whether in abnormal set Exception_FD_ISSET, to know Whether current socket is abnormal;
if(select.Exception_FD_ISSET(socket)){event.OnError(IOErr);
And previous cycle return is terminated by return;}
Step 7 reads the data that the barrage server received in socket is sent.
Mobile terminal reads the data that the barrage server received in socket is sent.Mobile terminal judges that socket is The no network data that can read barrage server, detailed process is as follows:
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 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.
The subscriber of a server error message is generated, must realize that all be abstracted of MessageObserver connects Mouthful function, specific implementation include: class ErrorMessageObserver:public MessageObserver public: Const std::set < std::string>&GetObserverMessageType () { defines a static container first Object types, static std::set<std::string>types;If types stored subscription in need Message then directly returns.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, and specific implementation function includes: map<int, and 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, since its same account logs in multiple equipment while logging in same Direct broadcasting room, barrage server can kick a client off.It not can be carried out reconnection then at this time.
KClientDisconnect=501 indicates that error code is 501, indicates that client has actively closed current chain It connects, therefore does not need to carry out reconnection.
}
Similarly define the error code that another map container storage does not need reconnection.
map<int,bool>mapNotRetry;
MapNotRetry [kTick]=false;
MapNotRetry [kClientDisconnect]=false.
Step 5 determines that the error code of specific message carrys out reconnection logic.
After receiving an error message, it is necessary first to whether need reconnection according to error code to inquire, then inquire again Whether reconnection is not needed, and specific process is as follows:
map<int,bool>::iterator itr;An iterator is defined first.
Itr=mapRetry.find (errorcode);Then the error code obtained from error message is used to carry out Inquiry.
{ 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, after obtaining token, then again carry out weight Even.
}
{ explanation has found else, illustrates not needing to carry out reconnection;The present embodiment can then call before pipe object Break function 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 five
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, Virtualconst std::set < std::string>&GetObserverMessageType ()=0;std::set< Std::string > expression can store multiple and different type of messages, and type of message cannot be identical.Then it defines another A abstraction interface 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 conststd:: 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, constchar* 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 six
It should be noted that on the basis of the above embodiments, the present invention can also have other implementations, for example, Network Environment designs link solution, and specific embodiment is as follows:
With popularizing for Internet protocol 6 (internet protocol version 6, IPV6), for mobile terminal For, the network of Internet protocol 4 (internet protocol version 4, IPV4) can be used, also can be used mutually The network of networking protocol 6 (internet protocol version 6, IPV6), and if barrage server itself is only supported The network of IPV4 then needs the address conversion that the client of mobile terminal is carried out IPV6 at the address of IPV4, passes through IPV4's Linked server is carried out in address.When being necessary to ensure that support link barrage, mobile terminal can also chain mutually in the environment of IPV6 The barrage server of networking protocol 4 (internet protocol version 4, IPV4).When based on multiple Internet protocols In the case of (internet protocol, IP) or domain name, available IP how is quickly selected, how to allow user to see as soon as possible Become primary problem to barrage.The present invention provides a solution, the specific steps are as follows:
Step 1 determines network type belonging to barrage server.
When client (installation is on mobile terminals) starts to link barrage server, since the IP of server is IPV4, thus regardless of it is local is IPV4 or IPV6, require to be converted into the network address of IPV4 to be linked, then client End then needs to judge to be currently the network of IPV4 or the network of IPV6, while to be also converted into IPV4 if it is the network of IPV6 Network.
Step 2 judges that current network environment is IPV4 or IPV6.
Current embodiment require that judging that current network is the network environment of IPV6, if it is explanation is IPV6, if It is not to illustrate it is currently IPV4.The present embodiment goes to link by defining the network address of an IPV6, if successfully explanation is worked as Preceding support is IPV6 network.For the IP address 2000::0 of IPV4 the present embodiment selection server, and for this implementation of IPV6 Example then uses 2000::0 to go to link as the address of server.It is implemented as follows:
Define the address information variable struct sockaddr_in addr of a socket;Addr.sin_len= Sizeof (sockaddr_in), addr.sin_family=AF_INET6, wherein being this time shown to be using IPV6, then to it Assignment is carried out, wherein port numbers use 80 ports, and then IP uses 2000:: being the address of an IPV6, addr.sin_port =80, addr.sin_addr.s_addr={ // 2000::0x20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }.
Then a socket is created, and uses User Datagram Protocol (user datagram protocol, UDP) Agreement, because whether the IP that the present embodiment is test current server can connect, the present embodiment uses UDP, because The speed ratio of UDP is very fast, int s=socket (pf, SOCK_DGRAM, IPPROTO_UDP).
Then calling system function connect is linked, int ret=connect (s, addr, addrlen);If Return value ret illustrates to link successfully for 0, otherwise link failure.If linked, successfully explanation is current to support IPV6, if successful Illustrate to be currently IPV6 network environment, be otherwise IPV4 network environment, link barrage clothes then can be directly carried out if it is IPV4 Business device.
Step 3, by the network address translation of IPV6 at the network address of IPV4.
It then also needs to carry out address conversion if it is IPV6, by system function socket_inet_ntop to the ground of IPV6 Location is converted into the address of IPV4.Be implemented as follows: the variable for defining an IPV4 first is with being used to store the IPV4 after conversion Location, char ipv4 [100]={ 0 };Following then calling system function socket_inet_ntop is converted, wherein parameter Addr.sin6_family indicates IPV6 address protocol, and wherein parameter addr.sin6_addr is the address of the IPV6 of input;Its Middle parameter IPV4 can then store conversion after as a result, socket_inet_ntop (addr.sin6_family, & (addr.sin6_ addr),ipv4,sizeof(ipv4)).Mobile terminal has determined whether current network environment is IPV4 or IPV6, if it is IPV6 is since server uses the address of IPV4 so needing to convert address, thus movement according to the present embodiment Terminal applies can also be linked to the barrage server of IPV4 under the network environment of IPV6.
Step 4 connects barrage server based on the address IPV4 after conversion.
When by the network address translation of IPV6 at IPV4 network address after, then mobile terminal can be directly connected to barrage clothes Business device.Establish the connection with server, int sockfd=socket (AF_INET, SOCK_STREAM, 0).Address family Servaddr.sin_family=ip;Port numbers (host byte sequence to network bytes sequence), servaddr.sin_port= htons(port);Calling system function connect starts to connect barrage server, then can directly be connected by connect Meet barrage server, int nRet=connect (sockfd, (struct sockaddr*) &servaddr, sizeof (servaddr))。
The embodiment of the present invention, the network address for being IPV4 by the network address translation of IPV6, it is ensured that mobile terminal is in IPV6 In the environment of can also chain only support IPV4 barrage server, improve link barrage treatment effeciency.
Embodiment seven
It should be noted that on the basis of the above embodiments, the present invention can also have other implementations, for example, The network switching of current network environment is monitored, reconnection design link solution, specific implementation are carried out based on monitored results Under such as:
Since mobile terminal device is usually mobile and PC equipment is widely different, process may with user into Line position sets movement, with the mobile switching that can then generate network.For example, WIFI use at home, then can be switched to 4G after going out, Network that may also be weak to signal for the very strong network switching of signal, and for viewing live streaming, need as far as possible discover net Network transformation, thus early link.Specifically, then needing to monitor current network from 4G network switching to WIFI network It is converted, to disconnect current network linking, reuses new network and linked, it can be faster new Barrage server is chained in network.And when from having network or strong signal network switching to no signal network or weak signal net When network, in order to save electricity, the overtime reconnection using network bottom layer is then needed at this time, and is set as more for a long time Time-out, allow bottom-layer network to carry out reconnection, electricity saved with this.The present embodiment is then linked according to android system to design The method of barrage, the specific steps are as follows:
Step 1 defines a network linking type to store current network type, and generates the state of network type Code.
The present embodiment defines a network linking type to store current network type, determines an enumerated variable to deposit Network type is stored up, NetStatus enumeration type is defined as.
enum NetStatus{
KNONET=1,
kWIFI,
k4G,
};
There is defined kNONET to indicate currently without network, and is assigned a value of 1;Defining kWIFI indicates current network For WIFI, then automatic assignment is 2;Defining k4G indicates that current network is 4G network, then automatic assignment is 3, is defined network-like 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.
If (prevStatus==curStatus) is { if as current network state with network state is before , then illustrate network there is no variation, then barrage link does not change.
{ if (prevStatus==kNONET) is { if be that no network is then needed now with network before by else Carry out barrage link.
The code of step 1 is continued to use to carry out network linking, int nRet=connect (sockfd, (struct sockaddr*)&servaddr,sizeof(servaddr));
Else if (prevStatus==kWIFI) is { if be before the network state for having the state of WIFI, and present Changed, need to disconnect the link of existing barrage if being 4G network now as soon as possible, using new network again into Row link.The Break function of pipe object before the present embodiment can then call disconnects current network linking.
After disconnecting network, pipe.Break ();Carry out reconnection operation again is needed, the code for continuing to use step 1 comes Carry out network linking, int nRet=connect (sockfd, (struct sockaddr*) &servaddr, sizeof (servaddr));
Else if (prevStatus==k4G) is { if be to belong to 4g network, and be now WIFI before, then It needs to carry out network disconnection at once, and links new network again.The present embodiment can then call before pipe object Break function disconnects current network linking.
After disconnecting network, pipe.Break ();Carry out reconnection operation again is needed, the code for continuing to use step 1 comes Carry out network linking, int nRet=connect (sockfd, (struct sockaddr*) &servaddr, sizeof (servaddr));
}
}
}
The embodiment of the present invention, when from having network or strong signal network switching to no signal network or weak signal network When, using the overtime reconnection of network bottom layer, and it is set as more prolonged time-out, allows bottom-layer network to carry out reconnection, with this Electricity is saved, the treatment effeciency of link barrage is improved.
Embodiment eight
It should be noted that on the basis of the above embodiments, the present invention can also have other implementations, for example, Link solution is designed based on quickly switching or selecting the IP that can be linked, specific embodiment is as follows:
In order to which the client ensured on mobile terminal can chain barrage server (server), usual server can be given The IP list of multiple servers selects to use for client out, and client can arbitrarily select the IP of a server as oneself Linked server IP.Existing rule of doing is the clothes selected an IP from IP list to be linked, but work as an IP There are failure, perhaps this network line breaks down and then needs client quickly to switch or select can to link business device IP.And for server there is also there is domain name in the case where, needing to parse domain name obtains more IP, selects chaining needs More suitable IP is linked out, to improve entire link speed.
Step 1, the data structure for defining IP and port.
Assuming that existing IP is listed as follows: ip1:119.23.45.6port:4002ip2:118.34.32.7port: 4002ip3:120.45.33.1port:4008ip4:121.55.23.8port:2009ip5:130.55.23.8port:4009; The present embodiment defines the structure of an ip and port, strcunt ipportitem { string ip;int port;Structure In include ip data and port data, then each ip and port can be stored by this ipportitem.
Step 2 determines barrage server domain name.
While providing barrage server ip, in order to improve the success rate of user's connection, link speed, domain name have There is the function that preferred network recently is carried out according to user's current geographic position.And also to prevent from not linking, provide One domain name danmu.dy.com client, needs quickly to pick out the ip that can be connected from these ip, so that subsequent can More quickly to connect barrage server.
Step 3, selection support the balanced IP of barrage server load.
In order to ensure that it is certain random that IP client that server provides can carry out, so that all clients will not It chooses the same IP and server is caused to collapse because of load too high.There is also some possibility, some ports of client simultaneously It is closed without server can be chained.Therefore upset at random and need to select the link that different ports is attempted.
Step 4 parses IP address according to barrage server domain name.
Client needs to parse domain name first, parses more IP address.Then the IP that translates domain names into and The IP that server issues is upset at random together, and system provides getaddrinfo function to translate domain names into IP address. The present embodiment can realize the conversion of domain name then with calling system function.The result of domain name transfer function can then be stored In struct addrinfo structure, so needing to define corresponding structure.Struct addrinfo hints, * single, result;The present embodiment defines 3 such structure variables.It needs to empty variable, memset (&hints, 0, sizeof (hints));Hints.ai_family=PF_INET;Hints.ai_socktype=SOCK_STREAM;Then to hints Information carries out assignment, and the present embodiment is to obtain the corresponding ip of domain name, so socktype is assigned a value of SOCK_STREAM.It connects down Carry out calling system function getaddrinfo to realize the parsing of domain name.getaddrinfo(host_name,NULL,&hints,& result);Wherein needing incoming parameter host_name is then domain name, danmu.dy.com function call in corresponding the present embodiment After the completion, it as a result can then store in hints and result;And a domain name parses multiple ip, then with chained list Form is stored into result.Next for circulation is write to traverse the ip list parsed.For (single= result;single;Single=single- > ai_next) { result is stored in result, and next result is then in ai_ In next structure, the present embodiment is obtained by traversing.Const char ip=single- > ai_addr.ip;In each chain In table structure, data are stored in this attribute of ip.
Step 5 generates a container object ipportitem item to store the multiple IP got.
The present embodiment designs vector<ipportitem>vecip;The present embodiment defines a container object to deposit Store up the IP, ipportitem item got.An item is created first, and assignment, item.ip=ip then are carried out to item; Item.port=port;vecip.push_back(item);By calling the push_back function of container then to arrive ip storage In container, while 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);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);All ip and port are all stored to this and arrived in vecip container.
Step 6 carries out random and upsets to the multiple IP got.
Next it needs to upset the data in vecip at random.Corresponding interface is provided for STL container Random_shuffle upsets the data in STL container at random.It is implemented as follows: random_shuffle (vecip.begin(),vecip.end());After calling this function of completion, all ip in container have been disturbed, After upsetting, the subsequent strategy of the present embodiment is to select 3 ip every time to be linked, therefore not have identical end in best one group of ip Slogan, if there is the identical exchange that can then carry out position with subsequent ip.
Step 7, according to IP link barrage server random and after upsetting.
Existing method is to carry out attempting to remove linked server by ip one by one and port.Such situation there may be times when The not upper time loss of the chain as caused by time-out is long.And the present embodiment then can successively select from container 3 ip come into Row attempts link, and the time-out that each ip is arranged 4 seconds disconnects other 2 ip's if having one to connect in 3 ip at once Link.
The present embodiment is initiated first ip and is linked when starting link first.Create web socket socket; Int sockfd=socket (AF_INET, SOCK_STREAM, 0) establishes the connection with server;Address family is created, Servaddr.sin_family=vecip [0] .ip;It creates port numbers (host byte sequence to network bytes sequence), Servaddr.sin_port=htons (vecip [0] .port);Then it is linked, int nRet=connect (sockfd,(struct sockaddr*)&servaddr,sizeof(servaddr));In 4 seconds, if link returns , then illustrate successful connection, illustrates that this ip link speed ratio is very fast, can be used, it is subsequent, it is linked based on this IP;And If without returning successfully or failing, the present embodiment can then be selected from vecip for this link from starting to be linked to 4 seconds Second ip is selected to be linked.Int sockfd1=socket (AF_INET, SOCK_STREAM, 0) establishes the company with server It connects;Create address family, servaddr1.sin_family=vecip [1] .ip;Create port numbers (host byte sequence to network word Save sequence), servaddr1.sin_port=htons (vecip [1] .port);Then it is linked, int nRet=connect (sockfd1,(struct sockaddr*)&servaddr1,sizeof(servaddr1));If similarly having spent 4 seconds not having There is the link for returning and opening third ip;Int sockfd2=socket (AF_INET, SOCK_STREAM, 0) is established and service The connection of device;Create address family, servaddr2.sin_family=vecip [2] .ip;Creating port numbers, (host byte sequence arrives Network bytes sequence), servaddr2.sin_port=htons (vecip [2] .port);So the present embodiment is opened in 12 seconds The link of 3 groups of ip, int nRet=connect (sockfd1, (struct sockaddr*) &servaddr2, sizeof are opened (servaddr2));If there is the link of any one ip returns, the present embodiment can all disconnect the link of other ip.To Illustrate that the ip linked circuits first returned are more preferable, link speed is faster.
The present embodiment then can successively select from container 3 ip to carry out trial link, than traditional approach more rapidly Connect barrage server.Improve the treatment effeciency of link barrage.
The embodiment of the present invention is described from the angle of the method for link barrage above, below from the angle of mobile terminal The embodiment of the present invention is described in degree.
Referring to Fig. 2, Fig. 2 is a kind of embodiment schematic diagram of possible mobile terminal provided in an embodiment of the present invention, packet It includes: generation unit 201, for generating the mapping table of storage state code;Certain unit 202, for determining that socket exists All possible state and status code during link barrage, the status code and the possible state correspond;Storage Unit 203, for storing the status code into the mapping table;Judging unit 204, for being judged according to the status code Whether barrage needs to carry out the inquiry of reconnection;Query unit 205, if status code needs to carry out barrage reconnection, for according to institute State status code link barrage server.
Optionally, in some possible implementations, generation unit 201 is specifically used for: Standard Template Library STL being called to hold The map container of device;Define a map<int, bool>type object mapStatus, wherein the int is the map container Key value, for storing the status code of socket;The bool is for storing whether current state code needs to carry out reconnection.
Optionally, in some possible implementations, certain unit 202 is specifically used for: generating socket Status code, the status code include kInitErr, kSocketThreadStart, kSocketThreadStartErr, KTcpConnectIpErr, kTcpConnectTimeoutErr, kTcpIOErr, kTcpDisConnectedbyRemote and kTcpDisConnected;The kInitErr is for indicating initialization error code;The kSocketThreadStart is used for Indicate socket initialization thread;The kSocketThreadStartErr is for indicating socket initialization thread error code; The kTcpConnectIpErr generates error code when for indicating that socket links ip;It is described KTcpConnectTimeoutErr is for indicating that socket generates time-out;The kTcpIOErr is for indicating that socket sends number According to generation io error code;The kTcpDisConnectedbyRemote is for indicating that socket is linked by server closing;Institute KTcpDisConnected is stated for indicating that socket link disconnects;Assignment is carried out to the status code, each status code takes Value is different.
Optionally, in some possible implementations, certain unit 202 is specifically also used to: calling enumerated variable type enum SocketStatus;Successively by kInitErr, kSocketThreadStart, kSocketThreadStartErr, KTcpConnectIpErr, kTcpConnectTimeoutErr, kTcpIOErr, kTcpDisConnectedbyRemote and KTcpDisConnected is assigned a value of 1,2,3,4,5,6,7,8.
Optionally, in some possible implementations, storage unit 203 is specifically used for: will need to carry out the shape of reconnection State code is assigned a value of true, and the status code for not needing to carry out reconnection is assigned a value of false.
Optionally, in some possible implementations, storage unit 203 is specifically also used to: calling mapStatus container Assignment is carried out to status code, wherein mapStatus [kInitErr]=true, mapStatus [kSocketThreadStart] =false, mapStatus [kSocketThreadStartErr]=true, mapStatus [kTcpConnectIpErr]= True, mapStatus [kTcpConnectTimeoutErr]=true, mapStatus [kTcpIOErr]=true, MapStatus [kTcpDisConnectedbyRemote]=false, mapStatus [kTcpDisConnected]=true. Wherein, parameters refer to other embodiments, and details are not described herein again.
Optionally, in some possible implementations, judging unit 204 is specifically used for: calling interface function bool GetRetryFlag (int nStauts) inquires the status code, wherein the GetRetryFlag is interface name, described Int nStauts indicates the status code of inquiry, and the bool is return value, and the return value is that reconnection barrage is wanted in true expression, The return value is that false indicates not reconnection barrage;The find interface of map container is called to be inquired.
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 mapping table for generating storage state code is performed the steps of when 311;Determine that socket owns during linking barrage Possible state and status code, the status code and the possible state correspond;The status code is stored to described In mapping table;Judge whether barrage needs to carry out the inquiry of reconnection according to the status code;If status code needs to carry out barrage weight Even, then barrage server is linked according to the status code.
Optionally, in a kind of possible embodiment, the processor is specifically used for: calling Standard Template Library STL container Map container;Define a map<int, bool>type object mapStatus, wherein the int is the map container Key value, for storing the status code of socket;The bool is for storing whether current state code needs to carry out reconnection.
Optionally, in a kind of possible embodiment, the processor is specifically used for: generating the state of socket Code, the status code include kInitErr, kSocketThreadStart, kSocketThreadStartErr, KTcpConnectIpErr, kTcpConnectTimeoutErr, kTcpIOErr, kTcpDisConnectedbyRemote and kTcpDisConnected;The kInitErr is for indicating initialization error code;The kSocketThreadStart is used for Indicate socket initialization thread;The kSocketThreadStartErr is for indicating socket initialization thread error code; The kTcpConnectIpErr generates error code when for indicating that socket links ip;It is described KTcpConnectTimeoutErr is for indicating that socket generates time-out;The kTcpIOErr is for indicating that socket sends number According to generation io error code;The kTcpDisConnectedbyRemote is for indicating that socket is linked by server closing;Institute KTcpDisConnected is stated for indicating that socket link disconnects;Assignment is carried out to the status code, each status code takes Value is different.
Optionally, in a kind of possible embodiment, the processor is specifically used for: calling enumerated variable type enum SocketStatus;Successively by kInitErr, kSocketThreadStart, kSocketThreadStartErr, KTcpConnectIpErr, kTcpConnectTimeoutErr, kTcpIOErr, kTcpDisConnectedbyRemote and KTcpDisConnected is assigned a value of 1,2,3,4,5,6,7,8.
Optionally, in a kind of possible embodiment, the processor is specifically used for: will need to carry out the status code of reconnection It is assigned a value of true, the status code for not needing to carry out reconnection is assigned a value of false.
Optionally, in a kind of possible embodiment, the processor is specifically used for: calling mapStatus container to shape State code carries out assignment, wherein and mapStatus [kInitErr]=true, mapStatus [kSocketThreadStart]= False, mapStatus [kSocketThreadStartErr]=true, mapStatus [kTcpConnectIpErr]= True, mapStatus [kTcpConnectTimeoutErr]=true, mapStatus [kTcpIOErr]=true, MapStatus [kTcpDisConnectedbyRemote]=false, mapStatus [kTcpDisConnected]=true. Wherein, parameters refer to other embodiments, and details are not described herein again.
Optionally, in a kind of possible embodiment, the processor is specifically used for: calling interface function bool GetRetryFlag (int nStauts) inquires the status code, wherein the GetRetryFlag is interface name, described Int nStauts indicates the status code of inquiry, and the bool is return value, and the return value is that reconnection barrage is wanted in true expression, The return value is that false indicates not reconnection barrage;The find interface of map container is called to be inquired.
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: generating the mapping table of storage state code;Determine set Connect word socket all possible state and status code during linking barrage, the status code and the possible state one One is corresponding;By status code storage into the mapping table;Judge whether barrage needs to carry out reconnection according to the status code Inquiry;If status code needs to carry out barrage reconnection, barrage server is linked according to the status code.
Optionally, in a kind of possible embodiment, it is specifically used for realizing when which is executed by processor Following steps: the map container of Standard Template Library STL container is called;Define a map<int, bool>type object MapStatus, wherein the int is the key value of the map container, for storing the status code of socket;The bool is used Whether need to carry out reconnection in storage current state code.
Optionally, in a kind of possible embodiment, it is specifically used for realizing when which is executed by processor Following steps: generating the status code of socket, the status code include kInitErr, kSocketThreadStart, kSocketThreadStartErr、kTcpConnectIpErr、kTcpConnectTimeoutErr、kTcpIOErr、 KTcpDisConnectedbyRemote and kTcpDisConnected;The kInitErr is for indicating initialization error code; The kSocketThreadStart is for indicating socket initialization thread;The kSocketThreadStartErr is used for Indicate socket initialization thread error code;The kTcpConnectIpErr is generated wrong when for indicating that socket links ip Error code;The kTcpConnectTimeoutErr is for indicating that socket generates time-out;The kTcpIOErr is for indicating Socket sends data and generates io error code;The kTcpDisConnectedbyRemote is for indicating socket by server Close link;The kTcpDisConnected is for indicating that socket link disconnects;Assignment is carried out to the status code, it is each The value of status code is different.
Optionally, in a kind of possible embodiment, it is specifically used for realizing when which is executed by processor Following steps: enumerated variable type enum SocketStatus is called;Successively by kInitErr, kSocketThreadStart, kSocketThreadStartErr、kTcpConnectIpErr、kTcpConnectTimeoutErr、kTcpIOErr、 KTcpDisConnectedbyRemote and kTcpDisConnected is assigned a value of 1,2,3,4,5,6,7,8.
Optionally, in a kind of possible embodiment, it is specifically used for realizing when which is executed by processor Following steps: will need the status code for carrying out reconnection to be assigned a value of true, and the status code for not needing to carry out reconnection is assigned a value of false。
Optionally, in a kind of possible embodiment, it is specifically used for realizing when which is executed by processor Following steps: calling interface function bool GetRetryFlag (int nStauts) inquires the status code, wherein described GetRetryFlag is interface name, and the int nStauts indicates the status code of inquiry, and the bool is return value, described Return value is that reconnection barrage is wanted in true expression, and the return value is that false indicates not reconnection barrage;Call the find of map container Interface is inquired.
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
Generate the mapping table of storage state code;
Determine socket all possible state and status code during linking barrage, the status code and it is described can The state of energy corresponds;
By status code storage into the mapping table;
Judge whether barrage needs to carry out the inquiry of reconnection according to the status code;
If status code needs to carry out barrage reconnection, barrage server is linked according to the status code.
2. the method according to claim 1, wherein the mapping table for generating storage state code includes:
Call the map container of Standard Template Library STL container;
Defining a map<int, bool>type object mapStatus, wherein the int is the key value of the map container, For storing the status code of socket;The bool is for storing whether current state code needs to carry out reconnection.
3. the method according to claim 1, wherein the determining socket is during linking barrage All possible state and status code, the status code include: with the possible state one-to-one correspondence
Generate socket status code, the status code include kInitErr, kSocketThreadStart, kSocketThreadStartErr、kTcpConnectIpErr、kTcpConnectTimeoutErr、kTcpIOErr、 KTcpDisConnectedbyRemote and kTcpDisConnected;
The kInitErr is for indicating initialization error code;The kSocketThreadStart is for indicating that socket is initial Change thread;The kSocketThreadStartErr is for indicating socket initialization thread error code;It is described KTcpConnectIpErr generates error code when for indicating that socket links ip;The kTcpConnectTimeoutErr is used Time-out is generated in expression socket;The kTcpIOErr generates io error code for indicating that socket sends data;It is described KTcpDisConnectedbyRemote is for indicating that socket is linked by server closing;The kTcpDisConnected is used It is disconnected in indicating that socket is linked;Assignment is carried out to the status code, the value of each status code is different.
4. according to the method described in claim 3, it is characterized in that, described carry out assignment, each status code to the status code Value difference include:
Call enumerated variable type enum SocketStatus;
Successively by kInitErr, kSocketThreadStart, kSocketThreadStartErr, kTcpConnectIpErr, KTcpConnectTimeoutErr, kTcpIOErr, kTcpDisConnectedbyRemote and kTcpDisConnected are assigned Value is 1,2,3,4,5,6,7,8.
5. the method according to claim 1, wherein described wrap status code storage into the mapping table It includes:
The status code for carrying out reconnection will be needed to be assigned a value of true, the status code for not needing to carry out reconnection is assigned a value of false.
6. according to the method described in claim 5, it is characterized in that, described will need the status code for carrying out reconnection to be assigned a value of True, the status code for not needing progress reconnection, which is assigned a value of false, includes:
MapStatus container is called to carry out assignment to status code, wherein mapStatus [kInitErr]=true, MapStatus [kSocketThreadStart]=false, mapStatus [kSocketThreadStartErr]=true, MapStatus [kTcpConnectIpErr]=true, mapStatus [kTcpConnectTimeoutErr]=true, MapStatus [kTcpIOErr]=true, mapStatus [kTcpDisConnectedbyRemote]=false, MapStatus [kTcpDisConnected]=true;The mapStatus [kInitErr]=true indicates mapStatus Key value is stored in container to be kInitErr and need to carry out barrage reconnection, the mapStatus [kSocketThreadStart] =false indicates that storage key value is kSocketThreadStart and does not need to carry out barrage reconnection, institute in mapStatus container Stating mapStatus [kSocketThreadStartErr]=true indicates that storage key value is in mapStatus container KSocketThreadStartErr and need to carry out barrage reconnection, mapStatus [the kTcpConnectIpErr]=true Indicate that storage key value is kTcpConnectIpErr and needs to carry out barrage reconnection, the mapStatus in mapStatus container [kTcpConnectTimeoutErr]=true indicates that storage key value is in mapStatus container KTcpConnectTimeoutErr and need to carry out barrage reconnection, the mapStatus [kTcpIOErr]=true is indicated Key value is stored in mapStatus container to be kTcpIOErr and need to carry out barrage reconnection, mapStatus [kTcpDisConnectedbyRemote]=false indicates that storage key value is in mapStatus container [kTcpDisConnectedbyRemote and do not need carry out barrage reconnection, the mapStatus [kTcpDisConnected] =true indicates that storage key value is kTcpDisConnected and needs to carry out barrage reconnection in mapStatus container.
7. any method in -5 according to claim 1, which is characterized in that described to judge that barrage is according to the status code It is no to need the inquiry for carrying out reconnection to include:
Calling interface function bool GetRetryFlag (int nStauts) inquires the status code, wherein described GetRetryFlag is interface name, and the int nStauts indicates the status code of inquiry, and the bool is return value, described Return value is that reconnection barrage is wanted in true expression, and the return value is that false indicates not reconnection barrage;
The find interface of map container is called to be inquired.
8. a kind of mobile terminal characterized by comprising
Generation unit, for generating the mapping table of storage state code;
Certain unit, it is described for determining socket all possible state and status code during linking barrage Status code and the possible state correspond;
Storage unit, for storing the status code into the mapping table;
Judging unit, for judging whether barrage needs to carry out the inquiry of reconnection according to the status code;
Query unit, if status code needs to carry out barrage reconnection, for linking barrage server according to the status code.
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.
CN201811067058.2A 2018-09-13 2018-09-13 Bullet screen linking method and mobile terminal Active CN109379638B (en)

Priority Applications (1)

Application Number Priority Date Filing Date Title
CN201811067058.2A CN109379638B (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
CN201811067058.2A CN109379638B (en) 2018-09-13 2018-09-13 Bullet screen linking method and mobile terminal

Publications (2)

Publication Number Publication Date
CN109379638A true CN109379638A (en) 2019-02-22
CN109379638B CN109379638B (en) 2021-01-01

Family

ID=65405597

Family Applications (1)

Application Number Title Priority Date Filing Date
CN201811067058.2A Active CN109379638B (en) 2018-09-13 2018-09-13 Bullet screen linking method and mobile terminal

Country Status (1)

Country Link
CN (1) CN109379638B (en)

Cited By (2)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
CN110139163A (en) * 2019-05-22 2019-08-16 武汉瓯越网视有限公司 A kind of method and relevant apparatus obtaining barrage
CN113115059A (en) * 2021-03-29 2021-07-13 武汉斗鱼鱼乐网络科技有限公司 Bullet screen connection monitoring method, device, equipment and storage medium

Citations (8)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
CN102111419A (en) * 2011-03-07 2011-06-29 浙江大学 Message middleware-based client automatic reconnection method
CN104301318A (en) * 2014-10-15 2015-01-21 北京国信灵通网络科技有限公司 Network reconnection method and device used for instant messaging application
US20150326924A1 (en) * 2008-12-31 2015-11-12 Tivo Inc. Real-time dvr programming
CN106488294A (en) * 2016-09-28 2017-03-08 乐视控股(北京)有限公司 Barrage information transfer, display packing and device
EP2769504B1 (en) * 2011-10-17 2017-04-19 Telefonaktiebolaget LM Ericsson (publ) Reconnection in a transmission tree
US20170208351A1 (en) * 2008-08-12 2017-07-20 Tivo Solutions Inc. Real-time dvr usage and reporting system
CN107172444A (en) * 2017-03-30 2017-09-15 武汉斗鱼网络科技有限公司 A kind of network direct broadcasting reconnection method and system
CN108400903A (en) * 2018-01-22 2018-08-14 济南浪潮高新科技投资发展有限公司 A kind of physical layer link status detection method and device

Patent Citations (9)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
US20170208351A1 (en) * 2008-08-12 2017-07-20 Tivo Solutions Inc. Real-time dvr usage and reporting system
US20150326924A1 (en) * 2008-12-31 2015-11-12 Tivo Inc. Real-time dvr programming
US20180220191A1 (en) * 2008-12-31 2018-08-02 Tivo Solutions Inc. Real-time dvr programming
CN102111419A (en) * 2011-03-07 2011-06-29 浙江大学 Message middleware-based client automatic reconnection method
EP2769504B1 (en) * 2011-10-17 2017-04-19 Telefonaktiebolaget LM Ericsson (publ) Reconnection in a transmission tree
CN104301318A (en) * 2014-10-15 2015-01-21 北京国信灵通网络科技有限公司 Network reconnection method and device used for instant messaging application
CN106488294A (en) * 2016-09-28 2017-03-08 乐视控股(北京)有限公司 Barrage information transfer, display packing and device
CN107172444A (en) * 2017-03-30 2017-09-15 武汉斗鱼网络科技有限公司 A kind of network direct broadcasting reconnection method and system
CN108400903A (en) * 2018-01-22 2018-08-14 济南浪潮高新科技投资发展有限公司 A kind of physical layer link status detection method and device

Cited By (4)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
CN110139163A (en) * 2019-05-22 2019-08-16 武汉瓯越网视有限公司 A kind of method and relevant apparatus obtaining barrage
CN110139163B (en) * 2019-05-22 2021-06-22 武汉瓯越网视有限公司 Method and related device for acquiring bullet screen
CN113115059A (en) * 2021-03-29 2021-07-13 武汉斗鱼鱼乐网络科技有限公司 Bullet screen connection monitoring method, device, equipment and storage medium
CN113115059B (en) * 2021-03-29 2022-07-05 武汉斗鱼鱼乐网络科技有限公司 Bullet screen connection monitoring method, device, equipment and storage medium

Also Published As

Publication number Publication date
CN109379638B (en) 2021-01-01

Similar Documents

Publication Publication Date Title
US11411897B2 (en) Communication method and communication apparatus for message queue telemetry transport
US8001254B1 (en) Translating switch and method
US8341218B2 (en) Technique for enabling a plurality of software components to communicate in a software component matrix environment
CN103188245A (en) Fight game server system
CN102025567A (en) Sharing access detection method and related device
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
CN109308202A (en) A kind of method and mobile terminal linking barrage
EP1917580B1 (en) Peer-to-peer communication system
US6842781B1 (en) Download and processing of a network management application on a network device
CN117544592A (en) Domain name resolution method, device, node, electronic equipment and storage medium
CN109275014A (en) A kind of method and mobile terminal linking barrage
CN104969533B (en) A kind of data package processing method and device
CN110896493B (en) Bullet screen linking method and mobile terminal
CN110896570B (en) Bullet screen linking method and mobile terminal
CN103297455B (en) Connection sharing method between browser and device
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
CN114390088B (en) Interaction method and device of EDPS (electronic data transfer protocol) through OPC UA client and OPC UA server
WO2023207278A1 (en) Message processing method and apparatus
Baeckstroem et al. Design of a contact service in a Jini-based spontaneous network
Son et al. An intelligent SDP discovery scheme using knowledge-based adaptive probing
CN115567957A (en) Network element access method and system
Cortes-Goicoechea et al. Scalability limitations of Kademlia DHTs when enabling Data Availability Sampling in Ethereum
Barisic et al. Advanced middleware support on wireless sensor nodes

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