iOS通过SocketRocket实现websocket的即时聊天

本文介绍了如何在iOS项目中使用SocketRocket库来实现WebSocket即时通讯功能,包括库的引入、连接的建立与断开、消息的发送与接收。通过简化的代码示例,展示了实现即时聊天功能的基本步骤,强调前端工作相对简单,主要依赖后台的支持。
摘要由CSDN通过智能技术生成

最近项目中要做即时通讯功能, 但没打算使用环信,融云等三方平台, 我查了一下资料,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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值