最近项目中要做即时通讯功能, 但没打算使用环信,融云等三方平台, 我查了一下资料,ios端实现起来还是比较简单的 ,我也写了一个小demo,和大家分享一下
首先到getHub上下载一个 FaceBook的 SocketRocket, 然后倒入工程; 我是直接使用 pod导入SocketRocket
首先pod导入SocketRocket
platform :ios, '8.0'
pod 'SocketRocket', '~> 0.5.0'
在控制器中导入头文件
#import <SocketRocket/SRWebSocket.h>
然后就可以使用webSocket了, 其实里面的东西也不是很多, 主要是: 1.打开连接 2.关闭连接 3.发送消息 4.接收消息;
简单粗暴的直接上代码吧
#import "ViewController.h"
#import "Masonry.h" // 实现自动布局的
#import <SocketRocket/SRWebSocket.h>
#define HHMainScreenWidth [UIScreen mainScreen].bounds.size.width
#define HHMainScreenHeight [UIScreen mainScreen].bounds.size.height
@interface ViewController ()<SRWebSocketDelegate, UITextFieldDelegate, UITextViewDelegate>
@property(nonatomic, strong)UITextView *shouField;
@property(nonatomic, strong)UITextField *FaField;
@property(nonatomic, strong)SRWebSocket *webSocket;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self createView];
}
// 启动 webSocket
- (void)setSocket {
_webSocket.delegate = nil;
[_webSocket close];
// _webSocket = [[SRWebSocket alloc] initWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"ws://114.55.57.51:8282"]]];
_webSocket = [[SRWebSocket alloc] initWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"ws://10.220.117.205:8081/websocket"]]];
_webSocket.delegate = self;
NSLog(@"Opening Connection...");
[_webSocket open];
}
// 协议方法 链接成功 给服务器发送id
- (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 didReceiveMessage:(id)message {
NSLog(@"接收的消息:%@", message);
self.shouField.text = message;
}
//