|
这几天工程少了静下心来玩玩WebSocket,发现还是挺有意思的,目前只是做做测试,有待研究更深入的东西
当然ios我引入了AsyncSocket库作为我的socket库,有兴趣的朋友可以谷歌一下这个东西,挺实用的
(补充)近期还玩了下基于python,html5和ios端的WebSocket,颇有感悟,大家有兴趣可以去谷歌下RockSocket,简单易用而且方便,是个很好的HTML5和ios端相互交流的socket框架。
php sever端:
ios 客户端.h:
//
// RootViewController.h
// myFirstSocket
//
// Created by Jahnny on 13-3-22.
// Copyright (c) 2013年 ownerblood. All rights reserved.
//
#import
@interface RootViewController : UIViewController
{
AsyncSocket *_asyncSocket;
}
@property (retain, nonatomic) IBOutlet UITextField *submitText;
@end
ios 客户端.m:
//
// RootViewController.m
// myFirstSocket
//
// Created by Jahnny on 13-3-22.
// Copyright (c) 2013年 ownerblood. All rights reserved.
//
#import "RootViewController.h"
@interface RootViewController ()
@end
@implementation RootViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (IBAction)pressTest:(id)sender {
if (!_asyncSocket)
{
[_asyncSocket release];
_asyncSocket=nil;
}
_asyncSocket = [[AsyncSocket alloc]initWithDelegate:self];
NSString *host = @"127.0.0.1";
int nPort = 9196;
NSError *error = nil;
//[_asyncSocket connectToHost:host onPort:nPort error:&error];
[_asyncSocket connectToHost:host onPort:nPort withTimeout:2 error:&error];
if (error!=nil) {
NSLog(@"连接失败:%@",error);
}else{
NSLog(@"连接成功");
}
}
- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
{
NSLog(@"Info___willDisconnectWithError");
//[self logInfo:FORMAT(@"Client Disconnected: %@:%hu", [sock connectedHost], [sock connectedPort])];
if (err) {
NSLog(@"错误报告:%@",err);
}else{
NSLog(@"连接工作正常");
}
[_asyncSocket release];
_asyncSocket = nil;
}
- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
NSLog(@"Info___didConnectToHost");
[sock readDataWithTimeout:-1 tag:0];
if (_submitText.text.length>0) {
[sock writeData:[_submitText.text dataUsingEncoding:NSUTF8StringEncoding] withTimeout:3 tag:1];
}else{
[sock writeData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.baidu.com"]] withTimeout:3 tag:1];
}
}
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
NSLog(@"Info___didReadData");
NSData *strData = [data subdataWithRange:NSMakeRange(0, [data length])];
NSString *msg = [[[NSString alloc] initWithData:strData encoding:NSUTF8StringEncoding] autorelease];
if(msg)
{
NSLog(@"%@",msg);
}
else
{
NSLog(@"错误");
}
[sock readDataWithTimeout:-1 tag:0];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)dealloc {
[_submitText release];
[super dealloc];
}
@end
|
|
|