AsyncSocke使用

1.下载ASyncSocket库源码
2.把ASyncSocket库源码加入项目:只需要增加RunLoop目录中的AsyncSocket.h、AsyncSocket.m、AsyncUdpSocket.h和AsyncUdpSocket.m四个文件。
3.在项目增加CFNetwork框架

在Framework目录右健,选择Add-->Existing Files... , 选择 CFNetwork.framework

1.链接到主机

#pragma mark 连接到服务器
- (BOOL)connectToServer
{
    if (socket == nil) {
        socket = [[AsyncSocket alloc] initWithDelegate:self];
        NSError *error = nil;
        if (![socket connectToHost:PHHost onPort:PHPort error:&error]) {
            return NO;
        } else {
            NSData *data = [[NSData alloc] init];
            [socket writeData:data withTimeout:10.0f tag:0];//发送数据到服务器
            
            return YES;
        }
        
    } else {
        [socket readDataWithTimeout:-1 tag:0];
        return YES;
    }
}

2.链接成功后掉用的回调方法

#pragma mark socket链接到主机
- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
    [sock readDataWithTimeout:-1 tag:0];
}

3.接收到服务器下发数据时调用的回调方法

#pragma mark socket接受到数据处理方法
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
    NSLog(@"did read data");
    NSString* message = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"message is: \n%@",message);
    if (tag == 2) {
        [socket disconnect];
    }
}

这时如果有客户端与之建立连接,比如通过telnet。会依次调用AsyncSocket 的delegate的如下方法:
onSocket:didAcceptNewSocket: AsyncSocket创建了新的Socket用于处理和客户端的请求,如果这个新socket实例你不打算保留(retain),那么将拒绝和该客户端连接
onSocket:wantsRunLoopForNewSocket:,提供线程的runloop实例给AsyncSocket,后者将使用这个runloop执行socket通讯的操作
onSocketWillConnect:,将要建立连接,这时可以做一些准备工作,如果需要的话
onSocket:didConnectToHost:port:,这个方法是建立连接后执行的,一般会在这里调用写入或者读取socket的操作
在Echo示例中,不打算执行多线程,也不想支持多客户端连接,而且服务器端和客户端将建立长连接。直至客户端断开连接,服务器端才释放相应的socket。

代码如下:

- (void)onSocket:(AsyncSocket *)sock didAcceptNewSocket:(AsyncSocket *)newSocket{
    if (!acceptSocket) {
        acceptSocket=[newSocket retain];
        NSLog(@"did accept new socket");
    }
}

- (NSRunLoop *)onSocket:(AsyncSocket *)sock wantsRunLoopForNewSocket:(AsyncSocket *)newSocket{
    NSLog(@"wants runloop for new socket.");
    return [NSRunLoop currentRunLoop];
}

- (BOOL)onSocketWillConnect:(AsyncSocket *)sock{
    NSLog(@"will connect");
    return YES;
}

- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port{
    NSLog(@"did connect to host");
    [acceptSocket readDataWithTimeout:-1 tag:1];
}

- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
    NSLog(@"did read data");
    NSString* message = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
    NSLog(@"message is: n%@",message);
    [acceptSocket writeData:data withTimeout:2 tag:1];
}

- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag{
    NSLog(@"message did write");
    [acceptSocket readDataWithTimeout:-1 tag:1];
}

- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err{
    NSLog(@"onSocket:%p willDisconnectWithError:%@", sock, err);
}

- (void)onSocketDidDisconnect:(AsyncSocket *)sock{
    NSLog(@"socket did disconnect");
    [acceptSocket release];
    acceptSocket=nil;
}
这里timeout设置为-1,这样就可以保持长连接状态。


你可能感兴趣的:(AsyncSocke使用)