2019-08-14 10:08:33 +08:00
|
|
|
|
//
|
|
|
|
|
// WSClient.m
|
|
|
|
|
// Doric
|
|
|
|
|
//
|
|
|
|
|
// Created by pengfei.zhou on 2019/8/14.
|
|
|
|
|
//
|
|
|
|
|
|
|
|
|
|
#import "DoricWSClient.h"
|
|
|
|
|
#import <SocketRocket/SRWebSocket.h>
|
|
|
|
|
#import "DoricUtil.h"
|
|
|
|
|
#import "DoricContextManager.h"
|
|
|
|
|
|
2019-10-12 14:48:19 +08:00
|
|
|
|
@interface DoricWSClient () <SRWebSocketDelegate>
|
|
|
|
|
@property(nonatomic, strong) SRWebSocket *websocket;
|
2019-08-14 10:08:33 +08:00
|
|
|
|
@end
|
|
|
|
|
|
|
|
|
|
@implementation DoricWSClient
|
|
|
|
|
- (instancetype)initWithUrl:(NSString *)url {
|
2019-10-12 14:48:19 +08:00
|
|
|
|
if (self = [super init]) {
|
2019-08-14 10:08:33 +08:00
|
|
|
|
_websocket = [[SRWebSocket alloc] initWithURL:[NSURL URLWithString:url]];
|
|
|
|
|
_websocket.delegate = self;
|
|
|
|
|
[_websocket open];
|
|
|
|
|
}
|
|
|
|
|
return self;
|
|
|
|
|
}
|
2019-10-12 14:48:19 +08:00
|
|
|
|
|
2019-08-14 10:08:33 +08:00
|
|
|
|
- (void)webSocketDidOpen:(SRWebSocket *)webSocket {
|
|
|
|
|
DoricLog(@"webSocketDidOpen");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
- (void)webSocket:(SRWebSocket *)webSocket didReceivePong:(NSData *)pongPayload {
|
|
|
|
|
DoricLog(@"webSocketdidReceivePong");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message {
|
|
|
|
|
NSData *jsonData = [message dataUsingEncoding:NSUTF8StringEncoding];
|
|
|
|
|
NSError *err;
|
|
|
|
|
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
|
|
|
|
|
options:NSJSONReadingMutableContainers
|
|
|
|
|
error:&err];
|
2019-10-12 14:48:19 +08:00
|
|
|
|
if (err) {
|
|
|
|
|
DoricLog(@"webSocketdidReceiveMessage parse error:%@", err);
|
2019-08-14 10:08:33 +08:00
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
NSString *source = [[dic valueForKey:@"source"] mutableCopy];
|
|
|
|
|
NSString *script = [dic valueForKey:@"script"];
|
2019-10-12 14:48:19 +08:00
|
|
|
|
for (NSValue *value in [[DoricContextManager instance] aliveContexts]) {
|
2019-08-14 10:08:33 +08:00
|
|
|
|
DoricContext *context = value.nonretainedObjectValue;
|
2019-10-12 14:48:19 +08:00
|
|
|
|
if ([source containsString:context.source]) {
|
2019-08-14 10:08:33 +08:00
|
|
|
|
[context reload:script];
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error {
|
|
|
|
|
DoricLog(@"webSocketdidFailWithError");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean {
|
|
|
|
|
DoricLog(@"webSocketdidCloseWithCode");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
- (void)close {
|
|
|
|
|
[self.websocket close];
|
|
|
|
|
}
|
|
|
|
|
@end
|