AsyncSocket的使用

AsyncSocket使用流程

  • 安装AsyncSocket
    • 拷贝AsyncSocket类到项目
  • 使用AsyncSocket
    1. set delegate
      @interface NetWork : NSObject<AsyncUdpSocketDelegate,AsyncSocketDelegate>
    2. init socket
      mainTcpSocket = [[AsyncSocket alloc] initWithDelegate:self];
    3. connect
	if (![mainTcpSocket connectToHost:broadCastHost onPort:mainPort error:&error]) {
		NSLog(@"连接消息发送失败,error:%@",error);
    }
    else{
        NSLog(@"连接消息发送成功");
    }
  • 接收TcpSocket
    1. set timeout
      [mainTcpSocket readDataWithTimeout:-1 tag:1];
    2. delegate receive
	- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
	{
    	[mainTcpSocket readDataWithTimeout:-1 tag:1];
    
	    NSString * receiveMessage = [[NSString alloc] initWithData:dataencoding:NSUTF8StringEncoding];
    
    	NSLog(@"收到消息:%@",receiveMessage);
}
  • 发送TcpSocket

[mainTcpSocket writeData:[self handleSendMessage:theMessage] withTimeout:-1 tag:1];

posted @ 2014-08-06 19:42  wisejoker  阅读(368)  评论(0编辑  收藏  举报