代码库> 其他> websocket  股票类
websocket  股票类
关注
上传者:飞不过的大海 分类:其他(Others)
查看次数:4033 下载次数:429
上传时间:2015-03-24 大小:47 B
首先  导入websocket库,下面附件里有,大家可以去下载哦。
然后  在appdelegate.m里面添加下面的代码方法


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{
    // 连接websocket
   [self reConnectWebSocket];
}


#pragma mark -
#pragma mark - SRWebSocketDelegate


- (void)reConnectWebSocket
{
    [self disConnectWebSocket];

// 连接websocket
    self.webSocket          = [[SRWebSocket alloc] initWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
self.webSocket.delegate = self;

    [self.webSocket open];
}


- (void)disConnectWebSocket
{
// 断开websocket连接

self.webSocket.delegate = nil;

    [self.webSocket close];
    self.webSocket = nil;
}


- (void)sendMsgByDict:(NSMutableDictionary *)dict
{
// 发送数据请求

    NSError *error      = nil;
    NSData *jsonData    = [NSJSONSerialization dataWithJSONObject:dict
                                                          options:NSJSONWritingPrettyPrinted
                                                            error:&error
                           ];
    if (jsonData.length <= 0 || error == nil)
    {
// 数据解析错误
        DEF_DEBUG(@"Error: %@", error);

        return;
    }

// 开始请求
NSString *params = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    [self.webSocket send:params];
}


// required


- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message
{
NSLog(@"Received "%@"", message);
}


// optional


- (void)webSocketDidOpen:(SRWebSocket *)webSocket
{
NSLog(@"Websocket Connected:%d", self.webSocket.readyState);
}


- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error
{
NSLog(@":( Websocket Failed With Error %@", error);

    self.webSocket = nil;
}


- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean
{
NSLog(@"WebSocket closed:%d", self.webSocket.readyState);

    self.webSocket = nil;
}


- (void)webSocket:(SRWebSocket *)webSocket didReceivePong:(NSData *)pongPayload;
{
NSLog(@"Websocket received pong");
}








以上代码都添加好了之后,哪里需要调用,就在哪个类里面做如下处理
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];


// 页面直接切换,更改websocket的委托对象
    [AppDelegate appDelegate].webSocket.delegate = self;
}


- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];


// 离开页面,置空websocket委托对象
    [AppDelegate appDelegate].webSocket.delegate = nil;
}


// required


- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message
{
NSLog(@"Received "%@"", message);
//此处做数据处理
}


// optional


- (void)webSocketDidOpen:(SRWebSocket *)webSocket
{
NSLog(@"Websocket Connected:%d", [AppDelegate appDelegate].webSocket.readyState);
}








收藏
我来说两句
发表评论
您还没有登录!请登录注册
所有评论(0
提示
sina weixin mail 回到顶部