GCDAsyncSocket
GCDAsyncSocket使用🍓连接socket🍊重连🍉pragma mark - 发送🥭关闭socket
🍌GCDAsyncSocketDelegate
GCDAsyncSocket是CocoaAsyncSocket第三方库中的其中一个类,本文介绍的就是基于这一个类来做快速的socket通信开发
GCDAsyncSocket使用
通过pod导入 pod ‘CocoaAsyncSocket’ 导入头文件 #import <GCDAsyncSocket.h> 声明变量 遵循代理
@interface ViewController
()<GCDAsyncSocketDelegate
>
@property
(nonatomic
, strong
) GCDAsyncSocket
*socket
;
@end
🍓连接socket
#pragma mark - 连接socket
- (void)didClickConnectSocket
:(id
)sender
{
if (self
.socket
== nil
)
self
.socket
= [[GCDAsyncSocket alloc
] initWithDelegate
:self delegateQueue
:dispatch_get_global_queue(0, 0)];
if (!self
.socket
.isConnected
){
NSError
*error
;
[self
.socket connectToHost
:@
"127.0.0.1" onPort
:8090 withTimeout
:-1 error
:&error
];
if (error
) NSLog(@
"%@",error
);
}
}
🍊重连
#pragma mark - 连接socket
- (IBAction
)didClickConnectSocket
:(id
)sender
{
if (self
.socket
== nil
)
self
.socket
= [[GCDAsyncSocket alloc
] initWithDelegate
:self delegateQueue
:dispatch_get_global_queue(0, 0)];
if (!self
.socket
.isConnected
){
NSError
*error
;
[self
.socket connectToHost
:@
"127.0.0.1" onPort
:8040 withTimeout
:-1 error
:&error
];
if (error
) NSLog(@
"%@",error
);
}
}
🍉pragma mark - 发送
#pragma mark - 发送
- (IBAction
)didClickSendAction
:(id
)sender
{
NSData
*data
= [self
.contentTF
.text dataUsingEncoding
:NSUTF8StringEncoding
];
[self
.socket writeData
:data withTimeout
:-1 tag
:10086];
}
🥭关闭socket
pragma mark
- 关闭socket
- (void)didClickCloseAction
:(id
)sender
{
[self
.socket disconnect
];
self
.socket
= nil
;
}
🍌GCDAsyncSocketDelegate
- (void)socket
:(GCDAsyncSocket
*)sock didConnectToHost
:(nonnull NSString
*)host port
:(uint16_t)port
{
NSLog(@
"连接成功 : %@---%d",host
,port
);
[self
.socket readDataWithTimeout
:-1 tag
:10086];
}
- (void)socketDidDisconnect
:(GCDAsyncSocket
*)sock withError
:(NSError
*)err
{
NSLog(@
"断开 socket连接 原因:%@",err
);
}
- (void)socket
:(GCDAsyncSocket
*)sock didReadData
:(NSData
*)data withTag
:(long)tag
{
NSLog(@
"接收到tag = %ld : %ld 长度的数据",tag
,data
.length
);
[self
.socket readDataWithTimeout
:-1 tag
:10086];
}
- (void)socket
:(GCDAsyncSocket
*)sock didWriteDataWithTag
:(long)tag
{
NSLog(@
"%ld 发送数据成功",tag
);
}