// OSI(开放式系统互联), 由ISO(国际化标准组织)制定
    // 1. 应用层
    // 2. 表示层
    // 3. 会话层
    // 4. 传输层
    // 5. 网络层
    // 6. 数据链接层
    // 7. 物理层
    
    // TCP/IP, 由美国国防部制定
    // 1. 应用层, HTTP, FTP, SMTP, DNS
    // 2. 传输层, TCP, UDP
    // 3. 网络层, IP
    // 4. 链路层, ARP, RARP
    
    // HTTP(短连接)
    // 1. 建立链接, 三次握手
    // 2. 断开链接, 四次挥手
    
    // 数据报文->数据包->数据帧->比特流(二进制)-->比特流->数据帧->数据包->数据报文
    
    // socket, "插口", "套接字", 长连接, 存在于应用层和传输层之间, 提供一种封装, 方便进行通信


下面详解Socket通信:

布局如下:

服务端代码:

 

//  Created by 韩俊强 on 15/12/25.
//  Copyright © 2015年 韩俊强. All rights reserved.

#import "ViewController.h"
// 使用CocoPods使用<>, 可以指定路径
#import 
#import "GNASocket.h"

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UITextField *portTF;
@property (weak, nonatomic) IBOutlet UITextView *message; // 多行文本输入框
@property (weak, nonatomic) IBOutlet UITextField *content;

@property (nonatomic, strong) GCDAsyncSocket *clientSocket;// 为客户端生成的socket

// 服务器socket
@property (nonatomic, strong) GCDAsyncSocket *serverSocket;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
}

// 服务端监听某个端口
- (IBAction)listen:(UIButton *)sender
{
    // 1. 创建服务器socket
    self.serverSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    
    // 2. 开放哪些端口
    NSError *error = nil;
    BOOL result = [self.serverSocket acceptOnPort:self.portTF.text.integerValue error:&error];
    
    // 3. 判断端口号是否开放成功
    if (result) {
        [self addText:@"端口开放成功"];
    } else {
        [self addText:@"端口开放失败"];
    }
}

// 发送
- (IBAction)sendMessage:(UIButton *)sender
{
    NSData *data = [self.content.text dataUsingEncoding:NSUTF8StringEncoding];
    [self.clientSocket writeData:data withTimeout:-1 tag:0];
    
    GNASocket *socket = [GNASocket defaultScocket];
    [socket.mySocket readDataWithTimeout:-1 tag:0];
}

// 接收消息
- (IBAction)receiveMassage:(UIButton *)sender
{
    [self.clientSocket readDataWithTimeout:-1 tag:0];
}


// textView填写内容
- (void)addText:(NSString *)text
{
    self.message.text = [self.message.text stringByAppendingFormat:@"%@\n", text];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    
}

#pragma mark - GCDAsyncSocketDelegate
// 当客户端链接服务器端的socket, 为客户端单生成一个socket
- (void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket
{
    [self addText:@"链接成功"];
    //IP: newSocket.connectedHost
    //端口号: newSocket.connectedPort
    [self addText:[NSString stringWithFormat:@"链接地址:%@", newSocket.connectedHost]];
    [self addText:[NSString stringWithFormat:@"端口号:%hu", newSocket.connectedPort]];
    // short: %hd
    // unsigned short: %hu
    
    // 存储新的端口号
    self.clientSocket = newSocket;
}

- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    NSString *message = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    [self addText:message];
}


@end


客户端代码:

 

 

//  Created by 韩俊强 on 15/12/25.
//  Copyright © 2015年 韩俊强. All rights reserved.
//

#import "SecondViewController.h"
#import 
#import "GNASocket.h"

@interface SecondViewController ()

@property (weak, nonatomic) IBOutlet UITextField *addressTF;
@property (weak, nonatomic) IBOutlet UITextField *portTF;
@property (weak, nonatomic) IBOutlet UITextField *message;

@property (weak, nonatomic) IBOutlet UITextView *content;

@property (nonatomic, strong) GCDAsyncSocket *socket;

@end

@implementation SecondViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
}

// 和服务器进行链接
- (IBAction)connect:(UIButton *)sender
{
    // 1. 创建socket
    self.socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    
    // 2. 与服务器的socket链接起来
    NSError *error = nil;
    BOOL result = [self.socket connectToHost:self.addressTF.text onPort:self.portTF.text.integerValue error:&error];
    
    // 3. 判断链接是否成功
    if (result) {
        [self addText:@"客户端链接服务器成功"];
    } else {
        [self addText:@"客户端链接服务器失败"];
    }
}

// 接收数据
- (IBAction)receiveMassage:(UIButton *)sender
{
    [self.socket readDataWithTimeout:-1 tag:0];
}

// 发送消息
- (IBAction)sendMassage:(UIButton *)sender
{
    [self.socket writeData:[self.message.text dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:0];
}


// textView填写内容
- (void)addText:(NSString *)text
{
    self.content.text = [self.content.text stringByAppendingFormat:@"%@\n", text];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark - GCDAsyncSocketDelegate

// 客户端链接服务器端成功, 客户端获取地址和端口号
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port
{
    [self addText:[NSString stringWithFormat:@"链接服务器%@", host]];
    
    GNASocket *socket = [GNASocket defaultScocket];
    socket.mySocket = self.socket;
}

// 客户端已经获取到内容
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    NSString *content = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    [self addText:content];
}

@end

为通信传值写一个单例:

 

//.h
#import 
#import 

@interface GNASocket : NSObject

@property (nonatomic, strong) GCDAsyncSocket *mySocket;

+ (GNASocket *)defaultScocket;

@end


//.m

#import "GNASocket.h"

@implementation GNASocket

+ (GNASocket *)defaultScocket
{
    static GNASocket *socket = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        socket = [[GNASocket alloc] init];
    });
    return socket;
}

@end

最终效果:



posted on 2016-11-14 22:33  鬼神杀破狼  阅读(866)  评论(0编辑  收藏  举报