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

來源:互聯網
上載者:User

標籤:

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

在搜尋了很多資料後,用square大神的SocketRocket進行實現,會比較簡單,同時URL和連接埠,發送訊息參數需要和後台約定好。

首先pod匯入SocketRocket

platform :ios, ‘7.0‘
pod ‘SocketRocket‘, ‘~> 0.5.0‘

 

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

 

 

在控制器中匯入標頭檔

#import <SocketRocket/SRWebSocket.h>

 

建立

SRWebSocket *webSocket;

簡單點,在viewDidLoad中執行個體化並且設定代理,連結URL和規定連接埠號碼,

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方法接受到訊息後會執行,輸出訊息內容:

完成~

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.