IOS Access WebSocket

Source: Internet
Author: User

1,websocket

WebSocket is a protocol specification proposed by HTML5. It realizes the browser and the server Full-duplex communication, can better save the server resources and the bandwidth, WebSocket has agreed a communication specification, through a handshake mechanism, the client (browser) and the server (webserver) can establish a similar TCP connection, So as to facilitate communication between c-s. Before the advent of WebSocket, web interaction was typically a short or long connection based on the HTTP protocol. WebSocket is the technology that is produced to solve the real-time communication between client and server. The WebSocket protocol is essentially a TCP based protocol that initiates a special HTTP request through the HTTP/HTTPS protocol to create a TCP connection for exchanging data, and the server then communicates with the client via this TCP connection. It is the biggest difference with HTTP is: WebSocket is a two-way communication protocol, after establishing the connection, the WebSocket server and the client negative actively send or receive data to each other, just like the socket.

2,websocket Advantages

Before Web server implemented push technology or instant messaging, with polling (polling), at the interval of characteristics (such as 1 seconds) by the browser automatically issued a request, the server's message is actively pulled back, in this case, we need to continue to send requests to the server, however, HTTP The header for the request is very long, and the data contained in it may be just a small value, which takes up a lot of bandwidth and server resources.

The great thing about the WebSocket API is that servers and clients can push information to each other at any time within a given timeframe. The browser and the server only need to do a handshake action, after establishing a connection, the server can actively transfer data to the client, the client can also send data to the server at any time. In addition, the header information exchanged between the server and the client is small.

3,websocket usage

"1" I use the pod import

Pod ' Socketrocket '
"2" Import library to the project after the first package of a Hhwebsocketmanager single case

. h
#import <Foundation/Foundation.h>
#import <SocketRocket.h>

extern nsstring * const Kneedpayordernote;
extern NSString * Const kwebsocketdidopennote;
extern NSString * Const kwebsocketdidclosenote;
extern NSString * Const kwebsocketdidreceivemessagenote;

@interface hhwebsocketmanager:nsobject
    //Get Connection Status
@property (nonatomic,assign,readonly) srreadystate Socketreadystate;

+ (Hhwebsocketmanager *) instance;

-(void) srwebsocketopen;//Open connection
-(void) srwebsocketclose;//close connection
-(void) SendData: (ID) data;//Send data


@ End

. M #import "HHWebSocketManager.h" NSString * Const KNEEDPAYORDERNOTE = @ "Kneedpayordernote";
NSString * Const KWEBSOCKETDIDOPENNOTE = @ "Kwebsocketdidreceivemessagenote";
NSString * Const KWEBSOCKETDIDCLOSENOTE = @ "Kwebsocketdidclosenote";

NSString * Const KWEBSOCKETDIDRECEIVEMESSAGENOTE = @ "Kwebsocketdidreceivemessagenote";
    @interface Hhwebsocketmanager () <SRWebSocketDelegate> {int _index;
    Nstimer * HEARTBEAT;
    
Nstimeinterval Reconnecttime;

} @property (Nonatomic,strong) Srwebsocket *socket;
    @end @implementation Hhwebsocketmanager + (Hhwebsocketmanager *) instance{static Hhwebsocketmanager *instance = nil;
    static dispatch_once_t predicate;
    Dispatch_once (&predicate, ^{Instance = [[Hhwebsocketmanager alloc] init];
    });
return Instance; #pragma mark-**************** public Methods-(void) srwebsocketopen{//If the same URL return if (SELF.SOC
    KET) {return; } self.socket = [[Srwebsocket alloc] InitwiThurlrequest: [nsurlrequest requestwithurl:[nsurl urlwithstring:@ "Youurl"]]];//here fill in your server address NSLog (@ "
    Requested WebSocket address:%@ ", self.socket.url.absoluteString);
    Self.socket.delegate = self;
Start the connection [Self.socket Open];
        }-(void) srwebsocketclose{if (self.socket) {[Self.socket close];
        Self.socket = nil;
    Destroy heartbeat when disconnecting [self destoryheartbeat]; } #define WEAKSELF (WS) __weak __typeof (&*self) weakself = self-(void) SendData: (ID) data {NSLog (@ "Socketsenddat
    
    A---------------%@ ", data);
    Weakself (WS);
    
    dispatch_queue_t queue = dispatch_queue_create ("Zy", NULL);
            Dispatch_async (Queue, ^{if (weakself.socket!= nil) {//Only Sr_open open to send method Ah, or to collapse
                
            if (weakSelf.socket.readyState = = Sr_open) {//Send data [Weakself.socket send:data]; else if (weakSelf.socket.readyState = = sr_connecting) {NSLog(@ "In connection, other methods will automatically synchronize the data after reconnection");
                    Every 2 seconds to detect a socket.readystate state, detect about 10 times///whenever the status is Sr_open, call [Ws.socket Send:data] Send data If 10 times are still not connected, then this send request is lost, this situation is the server problem, small probability//code a bit long, I will write a logic here good [sel
                
            F Reconnect]; else if (weakSelf.socket.readyState = sr_closing | | weakSelf.socket.readyState = = sr_closed) {//W
                Ebsocket disconnected, call reconnect method NSLog (@ "heavy");
            [Self reconnect];
            } else {NSLog (@ "No network, send failure, once disconnected network socket will be I set the nil");
        NSLog (@ "In fact, it is better to send a judgment before the network state is better, I write a bit obscure, socket==nil to express broken Nets");
}
    });
        #pragma mark-**************** private mothodes//re-(void) Reconnect {[Self srwebsocketclose];
    No more than a minute, so it'll only go back 5 times. 2^5 = + if (Reconnecttime > 64) {//your network condition is not very good, please check the network and retry return; } dispatch_after (Dispatch_tiMe (Dispatch_time_now, (int64_t) (Reconnecttime * nsec_per_sec)), Dispatch_get_main_queue (), ^{self.socket = nil;
        [Self srwebsocketopen];
    NSLog (@ "re-lian");
    
        });
    The exponential growth of the time 2 (reconnecttime = 0) {reconnecttime = 2;
    }else{Reconnecttime *= 2; }//Cancel Heartbeat-(void) destoryheartbeat {dispatch_main_async_safe (^{if (heartBeat) {if (heart Beat respondstoselector: @selector (isValid)]) {if ([heartBeat isValid]) {[HeartBeat INV
                    Alidate];
                HeartBeat = nil; }}}}//Initialize heartbeat-(void) initheartbeat {dispatch_main_async_safe (^{[Self dest
            Oryheartbeat]; The heartbeat is set to 3 minutes, and the NAT timeout is typically 5 minutes heartBeat = [Nstimer timerwithtimeinterval:3 target:self selector: @selector (sentheart) User
            Info:nil Repeats:yes]; and server-side conventions to send what as Heartbeat ID, as much as possible to reduce the heartbeat packet size [[Nsrunloop Currentrunloop] AddTimer:HeartBeat Formode:nsrunloopcommonmodes];

    }-(void) sentheart{//Send heartbeat and background can be agreed to send what content generally can call ping I sent him here according to the background requirements [self senddata:@ "Heart"];}
    Pingpong-(void) ping{if (self.socket.readyState = = Sr_open) {[Self.socket sendping:nil]; }} #pragma mark-socket delegate-(void) Websocketdidopen: (Srwebsocket *) WebSocket {/////0 times per normal connection Reco
        Nnecttime = 0;
    Open heartbeat [self initheartbeat];
        if (WebSocket = = Self.socket) {NSLog (@ "************************** socket connection succeeded **************************");
    [[Nsnotificationcenter Defaultcenter] Postnotificationname:kwebsocketdidopennote Object:nil];  }-(void) WebSocket: (Srwebsocket *) webSocket didfailwitherror: (nserror *) error {if (WebSocket = = Self.socket)
        {NSLog (@ "************************** socket connection failed **************************");
            _socket = nil;
    Connection failed to reconnect [self reconnect]; }}-(void) WebSocket: (SRWEBSOCket *) WebSocket Didclosewithcode: (nsinteger) code reason: (NSString *) reason Wasclean: (BOOL) Wasclean {if (websock
        ET = self.socket) {NSLog (@ "************************** socket connection disconnected **************************");
        NSLog (@ "closed connection, code:%ld,reason:%@,wasclean:%d", (long) code,reason,wasclean);
        [Self srwebsocketclose];
    [[Nsnotificationcenter Defaultcenter] Postnotificationname:kwebsocketdidclosenote Object:nil]; }/* This function is the PONG message sent by the receiving server, where the last one is to accept the pong message, here is to mention the heartbeat packet, in general, the establishment of a long connection will create a heartbeat packet for every time to notify the server, the client or online, This 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===%@", reply);
        }-(void) WebSocket: (Srwebsocket *) WebSocket didreceivemessage: (ID) message {if (WebSocket = = Self.socket) { NSLog (@ "************************** SocKet received the data ************************** ");
        NSLog (@ "My background agreement message is that the JSON format data receives data, parse it by format, and then send the data to the call layer");
        
        NSLog (@ "message:%@", message);
    [[Nsnotificationcenter Defaultcenter] Postnotificationname:kwebsocketdidreceivemessagenote object:message]; 

} #pragma mark-**************** Setter Getter-(srreadystate) socketreadystate{return self.socket.readyState;}

-(void) dealloc{[[Nsnotificationcenter Defaultcenter] removeobserver:self];}
 @end
"3" Use method

Invoke
[[socketrocketutility instance] Srwebsocketopen] where the socket needs to be opened;
Call
[[socketrocketutility instance] srwebsocketclose] When a disconnect is required;

"4" Use this framework the last one is important to pay attention to

This framework gives us the encapsulated Webscoket before calling its sendping SendData method, be sure to determine whether the current scoket is connected or not, and the program will crash if it is not a connection state.

"5" Add notice

    [[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (srwebsocketdidopen) name:@ " Kwebsocketdidopennote "Object:nil];
    [[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (srwebsocketdidreceivemsg:) name:@ " Kwebsocketdidreceivemessagenote "Object:nil];
-(void) Srwebsocketdidopen {
    NSLog (@ "open successfully");
    What you need to do after a successful operation ...
        
}

-(void) Srwebsocketdidreceivemsg: (nsnotification *) Note {
    //receive the message sent over by the server
    NSString * messages = note.object;< C12/>nslog (@ "%@", message);
}






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.