iOS經過SocketRocket實現websocket的即時聊天

以前公司的即時聊天用的是常輪循,一直都以爲很不科學,最近後臺說配置好了socket服務器,我高興地準備用asyncsocket,可是告訴我要用websocket,基於HTML5的,HTML5中提出了一種新的雙向通訊協議--WebSocket,本文嘗試採用這種技術來實現以上的實時聊天功能。ios

在搜索了不少資料後,用square大神的SocketRocket進行實現,會比較簡單,同時URL和端口,發送消息參數須要和後臺約定好。web

首先pod導入SocketRocketjson

platform :ios, '7.0'
pod 'SocketRocket', '~> 0.5.0'服務器

 

而後在搭建一個最簡單的頁面,只有一個輸入框和buttonwebsocket

 

 

在控制器中導入頭文件socket

#import <SocketRocket/SRWebSocket.h>async

 

建立spa

SRWebSocket *webSocket;代理

簡單點,在viewDidLoad中實例化而且設置代理,連接URL和規定端口號,code

webSocket.delegate = nil;

    [webSocket close];

    webSocket = [[SRWebSocket alloc] initWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"你的服務器URL和端口號"]]];

    webSocket.delegate = self;

    NSLog(@"Opening Connection...");

    [webSocket open];

記得要遵照協議<SRWebSocketDelegate>,實現delegate方法

#pragma mark - SRWebSocketDelegate

 

- (void)webSocketDidOpen:(SRWebSocket *)webSocket;{

    NSLog(@"Websocket Connected");

    NSError *error;

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:@{@"id":@"chat",@"clientid":@"hxz",@"to":@""} options:NSJSONWritingPrettyPrinted error:&error];

    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

    [webSocket send:jsonString];

}

 

- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error;{

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

    webSocket = nil;

}

 

- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message;{

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

}

 

- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean;{

    NSLog(@"WebSocket closed");

    webSocket = nil;

}

 

- (IBAction)sendMessage:(id)sender {

    NSError *error;

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:@{@"id":@"chat",@"clientid":@"hxz",@"to":@"mary",@"msg":@{@"type":@"0",@"content":self.textfield.text}} options:NSJSONWritingPrettyPrinted error:&error];

    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

    [webSocket send:jsonString];

    

}

 

其中webSocketDidOpen是在連接服務器成功後回調的方法,在這裏發送一次消息,把id 名字發送到服務器,告知服務器,

在send方法中有兩個選擇:

// Send a UTF8 String or Data.

- (void)send:(id)data;

 

// Send Data (can be nil) in a ping message.

- (void)sendPing:(NSData *)data;

 

第一個是須要發送JSON字符串格式的Data,必須把對象轉換成JSON字符串格式,不然報錯,第二種是發送NSData類型,並且根據註釋能夠爲nil

在文本框輸入消息,發送後在對方消息列表顯示成功:

對方發送消息給我這端時,didReceiveMessage方法接受到消息後會執行,輸出消息內容:

完成~

相關文章
相關標籤/搜索