ios客戶端websocket的helloworld

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

import “SocketRocket/SRWebSocket.h”

@interface ViewController : UIViewController
{
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
有出入

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章