CocoaAsyncSocket无疑是目前封装得最完善的Socket库了:支持异步TCP/UDP,支持GCD,Objective-C接口封装,同时还有日志跟踪功能,使用此日志跟踪,程序员可以很方便的进行调试。
文件如下:
如果想打开日志调试,很简单,导入需要的DDASLLogger.h头文件,创建DDASLLogger单利对象就可以了。
简单的演示如下:
1.在故事版布局
2.在ViewController.h文件中
//ViewController.h
//AysnSocket
#import <UIKit/UIKit.h>
#import"AsyncSocket.h"
@interfaceViewController : UIViewController
{
NSMutableArray*_scokets;//存放客户端的可变数组
AsyncSocket *_sendSocket;//发送端
AsyncSocket *_receScoket;//接收端
}@end
3.在ViewController.m文件中
// ViewController.m
// AysnSocket
#import "ViewController.h"
#import "AsyncSocket.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextView *msgView;
@property (weak, nonatomic) IBOutlet UITextField *ipField;
@property (weak, nonatomic) IBOutlet UITextField *sendField;
- (IBAction)coneClicked:(UIButton *)sender; //连接服务器
- (IBAction)sendClicked:(UIButton *)sender; //发送端发送消息
- (IBAction)disConeClicked:(UIButton *)sender; //断开连接
@end
@implementation ViewController
@synthesize msgView;
@synthesize ipField;
@synthesize sendField;
- (void)viewDidLoad {
[super viewDidLoad];
//1.初始化scokets数组,存储新的客户端scoket
_scokets = [NSMutableArray array];
//2.实例化发送端和接收端
_sendSocket = [[AsyncSocket alloc]initWithDelegate:self];
_receScoket = [[AsyncSocket alloc]initWithDelegate:self];
//3.接收端开始监听网络
NSError *error;
[_receScoket acceptOnPort:8888 error:&error];
}
#pragma mark - 代理方法
//接受到新的scoket
- (void)onSocket:(AsyncSocket *)sock didAcceptNewSocket:(AsyncSocket *)newSocket
{
//将新接收到的socket加入数组中
[_scokets addObject:newSocket];
//开始接受数据
[newSocket readDataWithTimeout:-1 tag:0];
}
//接收端收到信息
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
//接收数据
NSString *string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
//格式化数据
self.msgView.text = [NSString stringWithFormat:@"%@,%@,%@",self.msgView.text,self.ipField.text,string];
//循环读取
[sock readDataWithTimeout:-1 tag:0];
}
//连接服务器成功
- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
NSLog(@"%@",host);
NSLog(@"连接服务器成功");
}
//断开服务器成功
-(void)onSocketDidDisconnect:(AsyncSocket *)sock
{
NSLog(@"断开连接成功");
}
#pragma mark - 按钮事件
//建立连接
- (IBAction)coneClicked:(UIButton *)sender {
if (_sendSocket.isConnected)
{
[_sendSocket disconnect];
}
//客户端重新连接到主机
[_sendSocket connectToHost:self.ipField.text onPort:8888 withTimeout:30 error:nil];
}
//发送消息
- (IBAction)sendClicked:(UIButton *)sender {
//客户端发送数据
NSData *data = [self.sendField.text dataUsingEncoding:NSUTF8StringEncoding];
[_sendSocket writeData:data withTimeout:30 tag:0];
//清空数据
self.sendField.text = @"";
}
//断开服务器
- (IBAction)disConeClicked:(UIButton *)sender
{
if (_sendSocket.isConnected)
{
[_sendSocket disconnect];
}
}
@end
测试如下:
(1)打开电脑的网络设置,看一下ip和设置端口为8888
(2)运行程序,在演示中输入ip和消息
一开始: 输入ip和消息,然后连接服务器
连接成功服务器成功发送消息,数据发送成功
断开服务器:
断开服务器后,再尝试发送数据,是无法发送并显示在UITextView上的。
个人demo地址请点击这里