AsyncSocket关于TCP的用法

AsyncSocke是封装了CFSocket和CFSteam的TCP/IP socket网络库。它提供了异步操作,本地cocoa类的基于delegate的完整支持。在这里简单介绍一下AsyncSocket关于TCP的简单用法。

创建一个工程,然后用Cocoapods导入库 pod 'CocoaAsyncSocket', '~> 7.4.1'
建一个SocketServer对AsyncSocket进行简单封装一下。这样使用起来更加方便:

#import 

typedef void(^ConnectBlock)(BOOL success);

@interface SocketServer : NSObject
@property (nonatomic,copy) ConnectBlock block;
/**
 *  判断当前所用的IP地址和端口是否可链接
 *
 *  @param ip      服务器IP地址
 *  @param port    端口号
 *  @param timeOut 超时时间
 *  @param block   用来返回是否可链接(YES/NO)
 */
- (void)connect:(NSString *)ip port:(unsigned int)port timeOut:(int)timeOut block:(ConnectBlock)block;
/**
 *  用来上传数据
 *
 *  @param data 要上传的数据
 */
- (void)writeData:(NSData *)data;
@end
#import "SocketServer.h"
#import 

#define kLOGIN @"login"
#define kERROR @"error"

@interface SocketServer ()
@property (nonatomic,strong) AsyncSocket *socket;
@end

@implementation SocketServer

- (AsyncSocket *)socket
{
    if(!_socket)
    {
        _socket = [[AsyncSocket alloc] initWithDelegate:self];
    }
    return _socket;
}

- (void)connect:(NSString *)ip port:(unsigned int)port timeOut:(int)timeOut block:(ConnectBlock)block
{
    _block = block;
    NSError *err = nil;
    if(![self.socket connectToHost:ip onPort:port error:&err])
    {
        block(NO);
    }
}

- (void)writeData:(NSData *)data
{
    [self.socket writeData:data withTimeout:30 tag:1];
}

#pragma mark AsyncSocketDelegate
//链接成功
- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
    if(_block)
    {
        _block(YES);
    }
}

//上传数据给服务器
- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag
{
    NSLog(@"写入成功");
    [self.socket readDataToLength:8 withTimeout:30 tag:1];
}

//从服务器读取数据
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    if(tag == 1)
    {
        NSLog(@"读取成功");
        //使用通知来传值
        [[NSNotificationCenter defaultCenter] postNotificationName:kLOGIN object:data];
    }
}

//链接出错
- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
{
    if(_block)
    {
        _block(NO);
    }
    [self.socket disconnect];
}


- (void)onSocketDidDisconnect:(AsyncSocket *)sock
{
    NSLog(@"已经断开链接");
}

@end

这里是ViewController中的代码,其中kIP用的是另一台电脑的IP地址

#import "ViewController.h"
#import "FirstView.h"
#import "AppDelegate.h"
#import "SocketServer.h"

#define kLOGIN @"login"
#define kERROR @"error"
#define kIP @"192.168.31.128"
#define kPORT 8080


@interface ViewController ()
@property (nonatomic,strong) UITextField *userNameTF;
@property (nonatomic,strong) UITextField *userPWDTF;
@property (nonatomic,strong) UIButton *loginBtn;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(login:) name:kLOGIN object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(error:) name:kERROR object:nil];
    [self addViews];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (UITextField *)userNameTF
{
    if(!_userNameTF)
    {
        _userNameTF = [[UITextField alloc] initWithFrame:CGRectMake(50, 100, 100, 40)];
        _userNameTF.placeholder = @"请输入用户名";
        _userNameTF.backgroundColor = [UIColor blueColor];
    }
    return _userNameTF;
}

- (UITextField *)userPWDTF
{
    if(!_userPWDTF)
    {
        _userPWDTF = [[UITextField alloc] initWithFrame:CGRectMake(50, 180, 100, 40)];
        _userPWDTF.placeholder = @"请输入密码";
        _userPWDTF.backgroundColor = [UIColor blueColor];
    }
    return _userPWDTF;
}

- (UIButton *)loginBtn
{
    if(!_loginBtn)
    {
        _loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _loginBtn.frame = CGRectMake(50, 260, 100, 40);
        _loginBtn.backgroundColor = [UIColor redColor];
        [_loginBtn setTitle:@"登陆" forState:UIControlStateNormal];
        [_loginBtn addTarget:self action:@selector(didClickLogin) forControlEvents:UIControlEventTouchUpInside];
    }
    return _loginBtn;
}

//页面布局
- (void)addViews
{
    UINavigationController *NC = [[UINavigationController alloc] initWithRootViewController:self];
    ((AppDelegate *)[UIApplication sharedApplication].delegate).window.rootViewController = NC;
    [self.view addSubview:self.userNameTF];
    [self.view addSubview:self.userPWDTF];
    [self.view addSubview:self.loginBtn];
}

//屏幕触摸事件
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.userNameTF resignFirstResponder];
    [self.userPWDTF resignFirstResponder];
}

//登陆按钮点击事件
- (void)didClickLogin
{
    NSString *aString = [self.userNameTF.text stringByAppendingString:[NSString stringWithFormat:@"/%@",self.userPWDTF.text]];
    NSData *data = [aString dataUsingEncoding:NSUTF8StringEncoding];
    SocketServer *sock = [[SocketServer alloc] init];
    [sock connect:kIP port:kPORT timeOut:30 block:^(BOOL success) {
       if(success)
       {
           [sock writeData:data];
       }
        else
        {
            [[NSNotificationCenter defaultCenter] postNotificationName:kERROR object:@"链接出错"];
        }
    }];
}

//通知回传方法
- (void)login:(NSNotification *)notification
{
    FirstView *first = [[FirstView alloc] init];
    [self.navigationController pushViewController:first animated:YES];
}


- (void)error:(NSNotification *)notification
{
    NSString *aString = [notification object];
    NSLog(@"%@",aString);
}

@end

这里的FirstView仅仅只是一个简单的ViewController并没有做别的操作:

#import "FirstView.h"

@implementation FirstView

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor yellowColor];
}

@end

这里有代码的Demo

你可能感兴趣的:(AsyncSocket关于TCP的用法)