相对于原生的 socket,GCDAsyncSocket 封装的很简单,几行代码即可实现。
这里介绍 GCDAsyncSocket 的使用。
pod 导入
pod 'CocoaAsyncSocket' ,'~> 7.6.3'
#import <GCDAsyncSocket.h>
#define SocketHost @"172.19.203.106"
#define SocketPort 8081 //端口
<GCDAsyncSocketDelegate>
- (void)connect
{
if (self.socket == nil) {
self.socket = [[GCDAsyncSocket alloc]initWithDelegate:self delegateQueue:dispatch_get_global_queue(0, 0)];
if (self.socket.isConnected == NO) {
BOOL isSuccess = [self.socket connectToHost:SocketHost onPort:SocketPort error:nil];
if (!isSuccess) {
NSLog(@"连接失败");
}
}
}
}
-(void)send
{
NSData * data = [@"发送了" dataUsingEncoding:NSUTF8StringEncoding];
// -1 永不失效
[self.socket writeData:data withTimeout:-1 tag:1];
}
-(void)close
{
[self.socket disconnect];
self.socket = nil;
}
-(void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port
{
NSLog(@"连接成功");
// -1 永不失效
[self.socket readDataWithTimeout:-1 tag:1];
}
-(void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
NSLog(@"断开连接:%@",err.description);
}
-(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
NSString * msg = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"接受到消息:%@",msg);
// -1 永不失效
[self.socket readDataWithTimeout:-1 tag:1];
}
-(void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag
{
NSLog(@"已经发送成功");
}