"Go" ios based on websocket chat mechanism

Source: Internet
Author: User

Original URL: HTTP://WWW.JIANSHU.COM/P/21D9B3B94CFC

WebSocket makes it possible for the browser to provide support for sockets, providing a two-way, TCP-based connection between the browser and the server. Web developers can use WebSocket to build real-time web apps very easily.

1.WebSocket mechanism

The following is a brief introduction to the principle and operating mechanism of WebSocket.

WebSocket is a new protocol for HTML5. It realizes the browser and the server full-duplex communication, can better save the server resources and bandwidth and achieve real-time communication, it is based on TCP, the same as HTTP through TCP to transfer data, but it and HTTP the maximum difference is:

WebSocket is a two-way communication protocol, after establishing the connection, both the WebSocket server and the Browser/client Agent can send or receive data to each other proactively, just like a Socket.

WebSocket requires a TCP-like client and server-side handshake connection to communicate with each other after a successful connection.

Using the WebSocket mode client interacts with the server such as:


WebSocket is a Socket-like TCP long connection communication mode, once the WebSocket connection is established, subsequent data are transmitted in the form of a frame sequence. The client and the server are not required to re-initiate the connection request before the client disconnects the WebSocket connection or the servers end the connection. In the case of large amount of concurrency and high client-server interaction load, the consumption of network bandwidth resources is greatly saved, and the performance advantage is obvious, and the client sends and receives messages on the same persistent connection, and the real-time advantage is obvious.

2. Specific implementations of WebSocket in iOS

1> download WebSocket SDK and import the project inside

2> in the chat controller to import the header file agent, etc.

3> Specific Use

Connection port

_websocket.delegate = nil;

[_websocket Close];

_websocket = [[Srwebsocket alloc] initwithurlrequest:[nsurlrequest requestwithurl:[nsurl urlwithstring:@ "ws:// www.qsjia.com:7272 "]];

_websocket.delegate = self;

[_websocket Open];

NSLog (@ "Open success!");

[Self websocketdidopen:_websocket];

Implementing Proxy methods

#pragma srwebsocketdelegate

Connection Successful

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

{

NSLog (@ "Websocket Connected");

}

Connection failed

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

{

NSLog (@ ":( Websocket Failed with Error%@ ", error);

_websocket = nil;

}

Receiving processing of new messages

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

{

NSLog (@ "Received \"%@\ "", message);

SELF.STR = message;

Self.mymessage = [Chatviewcontroller dictionaryWithJsonString:self.str];

self.ping = [Self.mymessage objectforkey:@ "type"];

if ([self.ping isequaltostring:@ "say"]) {

[Self addmessage];

[Self.arr enumerateobjectsusingblock:^ (persondetail* _nonnull obj, Nsuinteger idx, BOOL * _nonnull stop) {

if ([Obj.myid integervalue] = = [self.mymessage[@ "Roomid"] integervalue]) {

[Self.arr Exchangeobjectatindex:idx withobjectatindex:0];

}

}];

[Self.tableview Reloaddata];

}

[Self.tableview Reloaddata];

}

Connection Close

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

{

NSLog (@ "WebSocket closed");

Self.title = @ "Connection closed! (see logs) ";

_websocket = nil;

}

The string to be sent by the login server (depending on the background settings)

Get Userdefault

Nsuserdefaults *userdefault = [Nsuserdefaults standarduserdefaults];

NSString *uid = [Userdefault objectforkey:@ "UID"];

Nsmutabledictionary *dic = [nsmutabledictionary dictionarywithobjectsandkeys:@ "Login", @ "type", @ "1", @ "room_id", UID, @ "Client_name", nil];

[DiC enumeratekeysandobjectsusingblock:^ (NSString * key, id obj, BOOL *stop) {

if ([Key isequaltostring:@ "Client_name"]) {

[DiC setvalue:@ ([uid intvalue]) forkey:@ "Client_name"];

}else if ([Key isequaltostring:@ "room_id"]) {

[DiC setvalue:@ ([@ "1" intvalue]) forkey:@ "room_id"];

}

}];

NSData *data = [nsjsonserialization datawithjsonobject:dic options:nsjsonwritingprettyprinted Error:NULL];

NSString *string = [[NSString alloc] initwithdata:d ata encoding:nsutf8stringencoding];

NSLog (@ "%@", string);

[_websocket send:string];

Exit the string to be sent by the server

Nsmutabledictionary *dic = [nsmutabledictionary dictionarywithobjectsandkeys:@ "Loginout", @ "type", nil];

NSData *data = [nsjsonserialization datawithjsonobject:dic options:nsjsonwritingprettyprinted Error:NULL];

NSString *string = [[NSString alloc] initwithdata:d ata encoding:nsutf8stringencoding];

[_websocket send:string];

WebSocket is generally used in conjunction with the database, the implementation of the logic to be based on the specific circumstances to determine.



Wen/1seven (author of Jane's book)
Original link: HTTP://WWW.JIANSHU.COM/P/21D9B3B94CFC
Copyright belongs to the author, please contact the author to obtain authorization, and Mark "book author".

"Go" ios based on websocket chat mechanism

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.