iOS中 HTTP/Socket/TCP/IP通信协议具体解释 韩俊强的博客

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS中 HTTP/Socket/TCP/IP通信协议具体解释 韩俊强的博客相关的知识,希望对你有一定的参考价值。

简介:

    // 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 <CocoaAsyncSocket/CocoaAsyncSocket.h>
#import "GNASocket.h"

@interface ViewController ()<GCDAsyncSocketDelegate>

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

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

// serversocket
@property (nonatomic, strong) GCDAsyncSocket *serverSocket;

@end

@implementation ViewController

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

// 服务端监听某个端口
- (IBAction)listen:(UIButton *)sender
{
    // 1. 创建serversocket
    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
// 当client链接server端的socket, 为client单生成一个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

client代码:

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

#import "SecondViewController.h"
#import <CocoaAsyncSocket.h>
#import "GNASocket.h"

@interface SecondViewController ()<GCDAsyncSocketDelegate>

@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];
    
}

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

// 接收数据
- (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

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

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

@end



为通信传值写一个单例:

//.h
#import <Foundation/Foundation.h>
#import <CocoaAsyncSocket.h>

@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

终于效果:

技术分享


技术分享

iOS开发人员交流群:446310206


GitHub 项目地址喜欢记得start一下哦!




以上是关于iOS中 HTTP/Socket/TCP/IP通信协议具体解释 韩俊强的博客的主要内容,如果未能解决你的问题,请参考以下文章

高级IO中socketpair实现进程间通信以及重定向

iOS开发多线程篇—线程间的通信

将 iOS 设备与非 iOS 设备通信

iOS开发多线程篇—线程间的通信

[翻译]Nativescript 中 Web 视图与 Android/IOS 的双向通信

iOS多线程---GCD中线程的通信