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方法接受到消息后会执行,输出消息内容:

完成~

相关文章
相关标签/搜索