iPhone wifi使用socket连接Internet

1.使用AsyncSocket(http://code.google.com/p/cocoaasyncsocket/)
来做为Socket的一个基础库.

2.在该库里面提供了一个EchoServer,我们可以利用这个程序直接在MAC系统上面运行一个测试服务器起来.

3.根据AsyncSocket(http://code.google.com/p/cocoaasyncsocket/wiki/iPhone)的WIKI将AsyncSocket加入到iPhone的工程里面,记得将TARGET_OS_IPHONE这个宏在工程上面给定义一下.

4.编译工程通过.

5.连接服务器代码:
**********************************************
// 建立一个Socket实体并连接到本地服务器的7777端口
_client = [[AsyncSocket alloc] initWithDelegate:self];
NSError *err = nil;
if (![_client connectToHost:@"127.0.0.1" onPort:7777 withTimeout:1.0f error:&err]) {
    NSLog(@"client net:%@", err);
}

// 添加事件响应函数
A:- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port;
B:- (void)onSocketDidSecure:(AsyncSocket *)sock;
C:- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err;
D:- (void)onSocketDidDisconnect:(AsyncSocket *)sock;
E:- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag;

// 在函数A中请求读取数据, AsyncSocket内部会在有接收到数据的时候调用函数E
[_client readDataWithTimeout:-1 tag:0];

// 函数E被调用过之后这个读取请求就结束了,我们不想让它结束掉, 所以在函数E结尾处加入, 这样读取过程就可以一直持继下去了
[_client readDataWithTimeout:-1 tag:0];

// 在函数A里面将传入的sock给记录下来,这就是我们连接的服务器的socket接口了
_server = sock;

// 发送数据到服务器
NSData* data;
[_server writeData:data withTimeout:-1 tag:1];
**********************************************

6.这样子我们基本就可以实现与服务器进行收发消息的过程了(注意:这些回调函数都是在主线程进行的,并未在其它的线程中)

7.其它的响应事件未去做过多关注, 请自行解决了.



=======================================================



参考一下,这是我之前做测试时的代码.看能不能帮上你什么忙.
这是之前写的一段使用方法也可以参考一下.http://www.cocoachina.com/bbs/read.php?tid-21242-fpage-2.html

复制代码

  1. @implementation AsyncSocketTestViewController








    // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        // 添加我们的代码在这里
        _recvBuffer = [[NSMutableArray alloc] init];
        _client = [[AsyncSocket alloc] initWithDelegate:self];
        NSError *err = nil;
        if (![_client connectToHost:@"127.0.0.1" onPort:7777 withTimeout:1.0f error:&err]) {
            NSLog(@"client net:%@", err);
        }
        
        
        [NSTimer scheduledTimerWithTimeInterval:1.f/60.f target:self selector:@selector(gameLoop) userInfo:nil repeats:YES];
    }




    - (void)didReceiveMemoryWarning {
        // Releases the view if it doesn't have a superview.
        [super didReceiveMemoryWarning];
        
        // Release any cached data, p_w_picpath, etc that aren't in use.
    }

    - (void)viewDidUnload {
        // Release any retained subviews of the main view.
        // e.g. self.myOutlet = nil;

        [NSThread currentThread].name = @"main thread";
        // 添加我们的代码在这里
        if (_client) {
            [_client disconnect];
            [_client release];
        }
        [_recvBuffer release];
    }


    - (void)dealloc {
        [super dealloc];
    }


    ////////////////////////////////////////////////////////////////////////////////////////////////////

    - (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
    {
        NSLog(@"thread(%@),onSocket:%p didConnectToHost:%@ port:%hu", [[NSThread currentThread] name], sock, host, port);
        
        // 等待数据接收
        [_client readDataWithTimeout:-1 tag:0];
    }

    - (void)onSocketDidSecure:(AsyncSocket *)sock
    {
        NSLog(@"thread(%@),onSocketDidSecure:%p", [[NSThread currentThread] name], sock);
    }

    - (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
    {
        NSLog(@"thread(%@),onSocket:%p willDisconnectWithError:%@", [[NSThread currentThread] name], sock, err);
    }

    - (void)onSocketDidDisconnect:(AsyncSocket *)sock
    {
        NSLog(@"thread(%@),onSocketDidDisconnect:%p", [[NSThread currentThread] name], sock);
    }

    - (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
    {
        NSLog(@"thread(%@),onSocket:%p, %d, %@", [[NSThread currentThread] name], sock, tag, data);
        
        NSData* xdata = [NSData dataWithData:data];
        [_recvBuffer addObject:xdata];
        
        NSString* s = @"xxyyff";
        NSData* ydata = [s dataUsingEncoding:NSUTF8StringEncoding];
        [sock writeData:ydata withTimeout:-1 tag:1];
        
        // 继续等待数据接收
        [_client readDataWithTimeout:-1 tag:0];
    }


    - (void)gameLoop
    {
        static int tag = 0;
        
        for (int i = 0; i < _recvBuffer.count; ++i) {
            NSData* data = [_recvBuffer objectAtIndex:i];
            
            NSString* msg = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
            NSLog(@"msg:%@", msg);
        }
        if (_recvBuffer.count) {
            [_recvBuffer removeAllObjects];
        }
        
        
        
        
        // 请求网络数据(并不一定在这次循环里面能得到)
        //[_client readDataWithTimeout:-1 tag:++tag];
        
    }