您的位置:首页 > 移动开发 > IOS开发

ios客户端websocket的helloworld

2015-08-20 14:32 441 查看
ios8,xcode6 
https://github.com/square/SocketRocket 
https://github.com/killinux/SocketRocket 
中的一个文件夹SocketRocket,3包含三个文件 
SRWebSocket.h

SRWebSocket.m

SocketRocket-Prefix.pch

copy到工程中 

Java代码  


//  

//  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  

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  

引入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 
有出入
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios websocket