iOS real-time chat based on the WebSocket protocol

Source: Internet
Author: User
Tags key string live chat

For a long time did not write a blog on the Cnblogs, but here wrote the earliest blog of the time stamp, really long ah, then did not graduate. Not in the Cnblogs period, in GitHub pages, Jane wrote a blog, github pages of markdown is still good, but Baidu can not retrieve the article, that is, through Baidu, can never guide the search to my article (touched moving), Pinterest feel more suitable for lyric chicken soup, I may not be able to fit into that user group. But now that I'm back, the article on GitHub pages, I'm not migrating, after all, life is not perfect, remind yourself not to have obsessive-compulsive disorder (heart meditation three times). The time of the last blog post (2016-04-29) continues back here, between two years and even longer. The approximate situation of this blank time is finished ~

---------------------a dirty split line---------------------

To the point, recently, because of the company's product needs, planning to develop live chat communication capabilities on the mobile side. Real-time chat third-party SDK vendors are also very much, because of the high degree of freedom of customization, data privacy and other aspects of consideration, the final server-client end is self-implementation, the server uses the worker man's PHP socket architecture.

On long-connected bidirectional communication, the WebSocket protocol is selected. Development is mainly responsible for the development of iOS client side, in accordance with the development of the third-party SDK standard, the key parts are encapsulated, only the necessary APIs for external calls, the relevant code is modularized, convenient later to the company's other projects to transplant the chat module. (You can't pit yourself, the likelihood of a transplant is very large, so instead of rambling writing code, it's better to follow the SDK standards for development.) )

WebSocket

The WebSocket agreement was born in 2008 and became an international standard in 2011. The WebSocket protocol is essentially a TCP-based protocol. is a full-duplex communication protocol based on the TCP protocol, which has good compatibility with the HTTP protocol. The default port is also 80 and 443, and the handshake phase with the HTTP protocol, so the handshake is not easy to block, through a variety of HTTP proxy server, so the server-side implementation is relatively easy. The protocol identifier isws,请求地址格式:ws://example.com:80/path

Handshake process:

In order to establish a WebSocket connection, the client first initiates an HTTP request to the server, which differs from the usual HTTP request and contains some additional header information. As shown below:

Client Request Header:

1 ---request Header--- 2 get/chat http/1.1 3 Upgrade:websocket 4 Connection:upgrade 5 host:127.0.0.1:8001 6 origin:http://127.0.0.1:8001 7 sec-websocket-key:hj0enqbhe/a0gkbxdrryyw== 8 sec-websocket-version:13

where the additional header information "Upgrade:websocket" indicates that this is a request protocol upgrade HTTP request, the server side resolves these additional header information, according to Sec-websocket-key string, through the SHA1 algorithm processing, will response information ( Sec-websocket-accept string) is returned to the client, the client can successfully decode the string, and the server-side Websocket connection is established.

Response of the server:

1 http/1.1 101 Switching Protocols 2 content-length:0 3 Upgrade:websocket 4 sec-websocket-accept:zes+c+vbk8aj01+wjgn7y15796g= 5 server:tornadoserver/4.5.1 6 Connection:upgrade 7 date:wed, June 03:29:14 GMT

The two sides can pass the information freely through this connection channel, and the connection will persist until one side of the client or the server side actively closes the connection.

Using the Socketrocket (OBJECTIVE-C) of the encapsulated WebSocket

Above is WebSocket handshake connection communication, and standing on the shoulders of giants, here is the Facebook Socketrocket project on GitHub, this is about WebSocket objective-c package, provides a simple API, Instead of having to deal with the underlying protocol, the developer focuses on the data processing, logic layer on the link. The features use of Socketrocket is described in detail on GitHub and is very simple to use. Note the relevant methods of the SRWEBSOCKETDELEGATE protocol:

Called when a message from the server is received, the message here is the ID type, either NSString or NSData.

-(void) WebSocket: (Srwebsocket *) WebSocket didreceivemessage: (ID) message;

Called when a connection to the server is established

-(void) Websocketdidopen: (Srwebsocket *) WebSocket;

Called when an unknown error occurs, possibly a network cause, etc.

-(void) WebSocket: (Srwebsocket *) webSocket didfailwitherror: (nserror *) error;

Called when WebSocket is closed

-(void) WebSocket: (Srwebsocket *) webSocket Didclosewithcode: (nsinteger) code reason: (NSString *) reason Wasclean: (BOOL ) Wasclean;

Called when a server's Pong is received

-(void) WebSocket: (Srwebsocket *) webSocket Didreceivepong: (NSData *) pongpayload;

Return Yes to convert messages, Send As NSString, return no, convert to skip nsdata->nsstring, pass directly to NSData. Default Yes

-(BOOL) websocketshouldconverttextframetostring: (Srwebsocket *) WebSocket;

This is similar to the socket communication you used when you learned Java, and the approximate flow is as follows: Init websocket, open, connected, sendmsg, handle server response Close

The specific code is also very easy to find on the Internet, it is not a small section of the paste code.

The above-mentioned channel handshake is established and can communicate with the server simple, it is necessary to consider a variety of situations, including broken network, poor signal, you need to consider the disconnection, send heartbeat packet to determine whether the server remains connected to the state.

Here the heartbeat packet is sent in a timed execution, using the Nstimer method.

1Dispatch_main_async_safe (^{2         3 [self destoryheartbeat];4         5__weaktypeof(self) weakself =Self ;6         //The heartbeat is set to 3 minutes and the NAT timeout is typically 5 minutes7_heartbeat = [Nstimer scheduledtimerwithtimeinterval:3* -Repeats:yes block:^ (Nstimer *_nonnull timer) {8NSLog (@"Heart");9             //and the server agreed to send what as a heartbeat identity, as much as possible to reduce the heartbeat packet sizeTen [Weakself sendheartbeatmessage]; One         }]; A [[Nsrunloop currentrunloop]addtimer:_heartbeat formode:nsrunloopcommonmodes]; -})

Error-Broken network and other re-connected implementation:

1- (void) Reconnect {2     3 [self stopsocket];4     5     if(_connectinterval <2) {6_connectinterval =2;7}Else{8_connectinterval = _connectinterval +2;9     }Ten      One     //re-establish the connection after each n+2 seconds after disconnecting ADispatch_after (Dispatch_time (Dispatch_time_now, (int64_t) (_connectinterval * nsec_per_sec)), Dispatch_get_main_ Queue (), ^{ - [self startsocket]; -     }); the}

A good connection with the server WebSocket module needs to be carefully polished, the show is a very rough module, need to be based on the needs of the future, the problem of continuous revision, in order to have a useful websocket module. Think of a sentence: the details determine success or failure . So polished every detail of life and work study ~

iOS real-time chat based on the WebSocket protocol

Related Article

Contact Us

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

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

A Free Trial That Lets You Build Big!

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

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

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

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