iOS Socket/Tcp编程 GCDAsyncSocket的实战(带回调)
Posted 溺水的小小鱼
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS Socket/Tcp编程 GCDAsyncSocket的实战(带回调)相关的知识,希望对你有一定的参考价值。
很多同学一听到Socket TCP UDP 这几个字眼感觉特别害怕,很怕在工作当中使用,因为他们太底层了.下面我把我在工作中使用Socket类库GCDAsyncSocket进行一次实战
文章中只适用于小型数据传输, 如果比较到,例如音频文件的话,请自行拼接data.
首先向工程导入GCDAsyncSocket.h/GCDAsyncSocket.m
下载地址:链接:http://pan.baidu.com/s/1c1bHytM密码: p22g
然后创建一个单例类Client 继承于NSObject
Client.h 文件内容如下
#import <Foundation/Foundation.h>
typedef void(^BLOCK)(idresult);
@interface RCClient : NSObject
+ (Client *)shareInstance;
- (void)sendMessage:(NSString *)strcomplete:(BLOCK)block;
@end
Client.m 文件内容如下:
#import "Client.h"
#import "GCDAsyncSocket.h"
// TCP连接
@interface Client ()
@property (nonatomic,strong)GCDAsyncSocket *socket;
@property (nonatomic,copy)BLOCK block;
@property (nonatomic,assign)NSInteger counter;
#define IP @"192.168.1.100"
#define PORT 5555
@end
@implementationClient
- (instancetype)init
{
self = [superinit];
if (self) {
[selfcreateConnection];
}
returnself;
}
+ (Client *)shareInstance {
staticClient *client =nil;
staticdispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
client = [[Clientalloc]init];
});
return client;
}
#pragma mark - 建立连接
- (void)createConnection {
self.socket = [[GCDAsyncSocketalloc]initWithDelegate:selfdelegateQueue:dispatch_get_main_queue()];
// 连接
NSError *error =nil;
[self.socketconnectToHost:IPonPort:PORTerror:&error];
if(error) {
NSLog(@"连接错误%@", error);
return;
}
[self.socketreadDataWithTimeout:-1tag:0];
}
// 发送数据
- (void)sendMessage:(NSString *)str tag:(NSInteger)tag complete:(BLOCK)block {
self.block = block;
[self.socketwriteData:[strdataUsingEncoding:NSUTF8StringEncoding]withTimeout:-1tag:0];
[self.socket readDataWithTimeout:-1 tag:0];
}
// tcp连接
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port {
NSLog(@"连接成功");
[self.socketreadDataWithTimeout:-1tag:0];
}
- (void)disconnection {
[self.socketdisconnect];
[self.socketreadDataWithTimeout:-1tag:0];
}
// 服务器返回数据
- (void)socket:(GCDAsyncSocket*)sock didReadData:(NSData *)data withTag:(long)tag {
NSString *str = [[NSStringalloc]initWithData:dataencoding:NSUTF8StringEncoding];
NSLog(@"str = %@", result);
self.block(result);
[self.socketreadDataWithTimeout:-1tag:0];
}
- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err {
NSLog(@"已经断开连接!");
[self.socketreadDataWithTimeout:-1tag:0];
}
@end
转自:http://blog.5ibc.net/p/32842.html
以上是关于iOS Socket/Tcp编程 GCDAsyncSocket的实战(带回调)的主要内容,如果未能解决你的问题,请参考以下文章
廖雪峰Java13网络编程-1Socket编程-2TCP编程