ios客户端websocket的helloworld

本文详细介绍了如何使用Objective-C结合SocketRocket库实现WebSocket实时通信的过程,包括库的引入、服务器端实例化、连接建立、消息接收与发送等关键步骤。同时提供了实例代码与相关库依赖说明,为开发者提供了一套完整的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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到工程中

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

[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
有出入
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值