WebSocket makes it possible for browsers to support sockets, thus providing a two-way TCP connection between the browser and the server. Web developers can easily build real-time Web applications using Websockets.
1. The WebSocket mechanism
The following is a brief introduction to the principle and operation mechanism of WebSocket.
WebSocket is a new protocol for HTML5. It realizes full-duplex communication between browser and server, which can better save server resources and bandwidth and achieve real-time communication. It is built on TCP, and transmits data through TCP like HTTP, but the biggest difference between it and HTTP is:
WebSocket is a two-way communication protocol. After the connection is established, both the WebSocket server and Browser/Client Agent can actively send or receive data to each other, just like Socket.
A WebSocket requires a TCP – like client and server to communicate with each other only after the connection is successful.
The interaction between the client and the server in WebSocket mode is shown as follows:
WebSocket is a TCP long-connection communication mode similar to Socket. Once a WebSocket connection is established, subsequent data is transmitted in the form of frame sequence. Before the client disconnects from the WebSocket or the Server, the client and Server do not need to initiate a connection request again. In the case of massive concurrency and heavy load traffic between client and server, it greatly saves the consumption of network bandwidth resources and has obvious performance advantages. In addition, the client sends and receives messages on the same persistent connection, which has obvious real-time advantages.
2. Specific implementation of WebSocket in iOS
1> Download the WebSocket SDK and import it into the project
2> Import header proxy in chat controller etc
3> Specific use
// Connect 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];
// Implement the proxy method
#pragma SRWebSocketDelegate
// The connection succeeded
– (void)webSocketDidOpen:(SRWebSocket *)webSocket;
{
NSLog(@”Websocket Connected”);
}
// Connection failed
– (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error;
{
NSLog(@”:( Websocket Failed With Error %@”, error);
_webSocket = nil;
}
// The new message is received
– (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];
}
// The connection is closed
– (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 when logging in to the server (depending on 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 :data encoding : NSUTF8StringEncoding];
//NSLog(@”%@”,string);
[_webSocket send:string];
// Exits 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 :data encoding : NSUTF8StringEncoding];
[_webSocket send:string];
WebSocket is generally used with the database, the implementation of the logic depends on the specific situation.
The original link: http://www.jianshu.com/p/21d9b3b94cfc