IOS Development Project-based on WebSocket chat (1) _ios

Source: Internet
Author: User
Tags http request

Company project needs to develop a similar QQ, micro-letter Instant IM chat function, do real-time monitoring messages, need to use the technology is websocket.

Overview WebSocket:

1.1 Why do we need to websocket such a real-time communication protocol?

WebSocket is a form of web communication, and the HTTP protocol, as we know it, is also a form of web communication. But we know that the HTTP protocol is a stateless protocol, its server itself does not have the ability to identify the client, must use some external information such as session and cookies, in order to maintain communication with specific clients. In other words, each HTTP request we send will take some information from the request header and cookies, this obviously increases the volume of the information we transmit and thus brings some network latency, which is intolerable for some applications that require high real-time communication. For example, chat programs or real-time games running in the browser. The most depressing thing is that these headers and cookies are often superfluous for a server to respond to a client's request, which means that although I bring this information to each request, the server and the client may not be able to use this information in the process of interaction.

To improve the network latency of HTTP requests, there are other ways to adapt to different requirements, such as polling, long polling (long-polling), data flow, eventsouce, and so on, and WebSocket is one of them.

In fact, most internet-based (or local area network) links typically contain long connections and two-way message exchange based on TCP sockets. However, the TCP protocol is the lowest level of network communication protocol, so that some untrusted client script to access the underlying TCP sockets is obviously not very safe, so WebSocket implemented a more secure scheme, It allows client script to create a two-way socket connection between the client and the server that supports the WebSocket protocol. This makes some of the network operations of real-time communication easier.

How does the 1.2 websocket work?

We know that the main role of WebSocket is to allow real-time communication between the server side and the client in full duplex (Full-duplex). Here's a good example: the HTTP protocol is like emailing, which must wait for the other to reply; WebSocket is like making a phone call, and the server and the client can send data to each other at the same time, and there is a continuous open data channel between them.

1.Pod Import Socketrocket

Platform:ios, ' 7.0 '

target ' white __socket--demo1 ' do

   pod ' socketrocket ', ' ~> 0.5.1 '

end

2. Import Object Srwebsocket

#import "ViewController.h"
#import "SRWebSocket.h"
@interface Viewcontroller () <SRWebSocketDelegate>
@property (Nonatomic,strong) srwebsocket *websocket;
@end

@implementation Viewcontroller

-(void) viewdidload {
  [super Viewdidload];


}

Initialize
-(void) reconnect{

  NSLog (@ "1221---open");

  Self.webSocket.delegate = nil;
  [Self.websocket close];

  Self.websocket = [[Srwebsocket alloc] initwithurlrequest:[nsurlrequest requestwithurl:[nsurl URLWithString:@ "ws:// 192.168.5.120:4141 "]]];
  Self.webSocket.delegate = self;
  Self.title = @ "Opening Connection ...";

  [Self.websocket open];
}

-(void) Viewwillappear: (BOOL) animated{
  [self reconnect];
}

-(void) Viewdiddisappear: (BOOL) animated{
  //close WebSocket
  self.webSocket.delegate = nil;
  [Self.websocket close];
  Self.websocket = nil;
 }

3.SRWebSocketDelegate

Connection Success//proxy method implementation #pragma mark-srwebsocketdelegate-(void) Websocketdidopen: (Srwebsocket *) websocket{NSLog (@ "Websocke
  T Connected ");
Self.title = @ "connected!";} Connection failure-(void) WebSocket: (Srwebsocket *) webSocket didfailwitherror: (Nserror *) error{NSLog (@ ":(

  Websocket Failed with Error%@ ", error); Self.title = @ "Connection failed!
  (logs) ";
 Self.websocket = nil; //Receive new message processing-(void) WebSocket: (Srwebsocket *) WebSocket didreceivemessage: (ID) message{//NSString *STR1 = Self.replyco
Ntent.text;
NSString *STR2 = [str1 stringbyappendingformat:@ "%@\n", message];

  Self.replyContent.text = str2;

 NSLog (@ "%@--ASKL", message); }//Connection closed-(void) WebSocket: (Srwebsocket *) webSocket Didclosewithcode: (nsinteger) code reason: (NSString *) reason
  Wasclean: (BOOL) wasclean{NSLog (@ "Closed reason:%@", Reason); Self.title = @ "Connection closed!
  (logs) ";
 Self.websocket = nil; //This function is sent by the receiving server Pong message, the last one is to accept the pong message, here is to mention the heartbeat packet, in general, establish a long connection will build a heartbeat packet for every time to notify the server, the client or online, thisA heartbeat packet is actually a ping message, my understanding is to create a timer, every 10 seconds or 15 seconds to send a ping message to the server, the message is empty-(void) WebSocket: (Srwebsocket *) webSocket Didreceivepong: (NSData *) pongpayload{nsstring *reply = [[NSString alloc] Initwithdata:pongpayload Encoding:NSUTF8Stri
  Ngencoding];
 NSLog (@ "%@", reply);
  } #pragma mark-sendbutton Response-(ibaction) SendAction: (ID) Sender {[Self.view endediting:yes]; WebSocket if (self.websocket) {[Self.websocket send:@] Hello!

  "];

 }
}

Implementation effect:

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.