---
title: "ios客户端websocket的helloworld"
author: "haoningabc"
date: "2014-10-09T02:11:14Z"
tags: ["Xcode", "iOS"]
categories: ["移动开发"]
slug: "ios-websocket-helloworld"
draft: false
lastmod: "2014-10-09T02:20:54Z"
id: 2125460
url: "https://haoningabc.iteye.com/blog/2125460"
---

ios8，xcode6 \[url]https://github.com/square/SocketRocket\[/url] \[url]https://github.com/killinux/SocketRocket\[/url] 中的一个文件夹SocketRocket，3包含三个文件 SRWebSocket.h SRWebSocket.m SocketRocket-Prefix.pch copy到工程中 \[code="java"] // // ViewController.h // TestWebs // // Created by xiao7 on 14-10-9. // Copyright (c) 2014年 killinux. All rights reserved. // #import #import "SocketRocket/SRWebSocket.h" @interface ViewController : UIViewController { SRWebSocket \*webSocket; } @end \[/code] \[code="java"] // // 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 \[/code] 引入4个库 libicucore.dylib，CFNetwork.framework, Security.framework, Foundation.framework \[img]http://dl2.iteye.com/upload/attachment/0101/7570/f59a16de-6e95-3d06-8f89-3eb412418931.png\[/img] server的例子参考 \[url]http://haoningabc.iteye.com/blog/2124605\[/url] 以上部分参考 参考http://nonocast.cn/websocket-in-objective-c/ 参考http://wenxin2009.iteye.com/blog/1707304 有出入