AsyncSocket使用流程
- 安装AsyncSocket
- 拷贝AsyncSocket类到项目
- 使用AsyncSocket
- set delegate
@interface NetWork : NSObject<AsyncUdpSocketDelegate,AsyncSocketDelegate>
- init socket
mainTcpSocket = [[AsyncSocket alloc] initWithDelegate:self];
- connect
- set delegate
if (![mainTcpSocket connectToHost:broadCastHost onPort:mainPort error:&error]) {
NSLog(@"连接消息发送失败,error:%@",error);
}
else{
NSLog(@"连接消息发送成功");
}
- 接收TcpSocket
- set timeout
[mainTcpSocket readDataWithTimeout:-1 tag:1];
- delegate receive
- set timeout
- (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];