https://github.com/square/SocketRocket
https://github.com/killinux/SocketRocket
中的一个文件夹SocketRocket,3包含三个文件
SRWebSocket.h
SRWebSocket.m
SocketRocket-Prefix.pch
copy到工程中
// // ViewController.h // TestWebs // // Created by xiao7 on 14-10-9. // Copyright (c) 2014年 killinux. All rights reserved. // #import <UIKit/UIKit.h> #import "SocketRocket/SRWebSocket.h" @interface ViewController : UIViewController<SRWebSocketDelegate> { SRWebSocket *webSocket; } @end
// // ViewController.m // TestWebs // // Created by xiao7 on 14-10-9. // Copyright (c) 2014年 killinux. All rights reserved. // #import "ViewController.h" @interface ViewController () @property (weak, nonatomic) IBOutlet UILabel *showTxt; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. webSocket.delegate = nil; [webSocket close]; webSocket = [[SRWebSocket alloc] initWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"ws://192.168.0.102:8887"]]]; webSocket.delegate = self; [webSocket open]; NSLog(@"open success!"); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (void)webSocketDidOpen:(SRWebSocket *)webSocket; { NSLog(@"Websocket Connected"); self.title = @"Connected!"; } - (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); self.showTxt.text = message; } - (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean; { NSLog(@"WebSocket closed"); self.title = @"Connection Closed! (see logs)"; webSocket = nil; } @end
引入4个库
libicucore.dylib,CFNetwork.framework, Security.framework, Foundation.framework
server的例子参考
http://haoningabc.iteye.com/blog/2124605
以上部分参考
参考http://nonocast.cn/websocket-in-objective-c/
参考http://wenxin2009.iteye.com/blog/1707304
有出入