iOS进阶2 -- CocoaAsyncSocket和Websocket框架使用

来源:互联网 发布:网络借贷利息是多少 编辑:程序博客网 时间:2024/04/26 09:33

一、CocoaAsyncSocket部分
本部分转自:http://www.jianshu.com/p/68100d518468
客户端代码地址:https://github.com/edwardGG/SocketClient
服务端代码地址:https://github.com/edwardGG/SocketServer
CocoaAsyncSocket比较好的博客:
http://blog.csdn.net/zhu410289616/article/details/46731605
直接看代码:

1.客户端代码

#import "ViewController.h"#import "GCDAsyncSocket.h"@interface ViewController ()<GCDAsyncSocketDelegate>@property (weak, nonatomic) IBOutlet UITextField *addressTF;@property (weak, nonatomic) IBOutlet UITextField *portTF;@property (weak, nonatomic) IBOutlet UITextField *messageTF;@property (weak, nonatomic) IBOutlet UITextView *showMessageTF;//客户端socket@property (nonatomic) GCDAsyncSocket *clinetSocket;@end@implementation ViewController#pragma mark - GCDAsynSocket Delegate- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port{    [self showMessageWithStr:@"链接成功"];    [self showMessageWithStr:[NSString stringWithFormat:@"服务器IP : %@", host]];    [self.clinetSocket readDataWithTimeout:-1 tag:0];}//收到消息- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{    NSString *text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];    [self showMessageWithStr:text];    [self.clinetSocket readDataWithTimeout:-1 tag:0];}- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{    [self.view endEditing:YES];}//开始连接- (IBAction)connectAction:(id)sender {    //2、连接服务器    [self.clinetSocket connectToHost:self.addressTF.text onPort:self.portTF.text.integerValue withTimeout:-1 error:nil];}//发送消息- (IBAction)sendMessageAction:(id)sender {    NSData *data = [self.messageTF.text dataUsingEncoding:NSUTF8StringEncoding];    //withTimeout -1 :无穷大    //tag: 消息标记    [self.clinetSocket writeData:data withTimeout:-1 tag:0];}//接收消息- (IBAction)receiveMessageAction:(id)sender {    [self.clinetSocket readDataWithTimeout:11 tag:0];}- (void)showMessageWithStr:(NSString *)str{    self.showMessageTF.text = [self.showMessageTF.text stringByAppendingFormat:@"%@\n", str];}- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.    //1、初始化    self.clinetSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];}- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}@end

说明:1.引入GCDAsyncSocket.h头文件
2.初始化GCDAsyncSocket对象,并设置代理
3.根据发出和接收到的信息进行处理。

2.服务端代码

#import "ViewController.h"#import "GCDAsyncSocket.h"@interface ViewController ()<GCDAsyncSocketDelegate>@property (weak, nonatomic) IBOutlet UITextField *portF;@property (weak, nonatomic) IBOutlet UITextField *messageTF;@property (weak, nonatomic) IBOutlet UITextView *showContentMessageTV;//服务器socket(开放端口,监听客户端socket的链接)@property (nonatomic) GCDAsyncSocket *serverSocket;//保护客户端socket@property (nonatomic) GCDAsyncSocket *clientSocket;@end@implementation ViewController#pragma mark - 服务器socket Delegate- (void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket{   //保存客户端的socket    self.clientSocket = newSocket;    [self showMessageWithStr:@"链接成功"];    [self showMessageWithStr:[NSString stringWithFormat:@"服务器地址:%@ -端口: %d", newSocket.connectedHost, newSocket.connectedPort]];    [self.clientSocket readDataWithTimeout:-1 tag:0];}//收到消息- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{    NSString *text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];    [self showMessageWithStr:text];    [self.clientSocket readDataWithTimeout:-1 tag:0];}//发送消息- (IBAction)sendMessage:(id)sender {    NSData *data = [self.messageTF.text dataUsingEncoding:NSUTF8StringEncoding];    //withTimeout -1:无穷大,一直等    //tag:消息标记    [self.clientSocket writeData:data withTimeout:-1 tag:0];}//开始监听- (IBAction)startReceive:(id)sender {    //2、开放哪一个端口    NSError *error = nil;    BOOL result = [self.serverSocket acceptOnPort:self.portF.text.integerValue error:&error];    if (result && error == nil) {        //开放成功        [self showMessageWithStr:@"开放成功"];    }}//接受消息,socket是客户端socket,表示从哪一个客户端读取消息- (IBAction)ReceiveMessage:(id)sender {    [self.clientSocket readDataWithTimeout:11 tag:0];}- (void)showMessageWithStr:(NSString *)str{    self.showContentMessageTV.text = [self.showContentMessageTV.text stringByAppendingFormat:@"%@\n",str];}- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.    // 1、初始化服务器socket,在主线程力回调    self.serverSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];    }- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}@end

说明:客户端和服务端工程同时运行在模拟器上,客户端的IP地址要写自己电脑的,端口号要和服务端的相同。

二、Websocket部分

本部分转自:http://www.cocoachina.com/ios/20160527/16482.html
Websocket第三方开源框架:facebook的SocketRocket框架
github地址:https://github.com/facebook/SocketRocket

0 0