TCP移動端跟伺服器資料互動

來源:互聯網
上載者:User

標籤:

同一台筆記本下的用戶端和服務端

TCPClient 用戶端:

//  RootViewController.h
#import <UIKit/UIKit.h>
#import "AsyncSocket.h"  //封裝了基於tcp協議的socket編程
//tcp協議是位於網路傳輸層的協議,規定用戶端與服務端之間、或者是用戶端與用戶端之間資料通訊的方式
//每個用戶端或者服務端通過ip地址+連接埠來標識
/*用戶端與服務端基於tcp協議進行資料通訊
 *1、用戶端需要通過ip+連接埠串連指定的伺服器
 *2、串連成功後,用戶端可以向服務端發送資料
 *3、服務端能夠接收資料,並進行後續處理
 *4、如果用戶端與服務端中斷連線,服務端能夠知曉
 5、AsyncSocket的使用方法->檔案夾直接拖拽進工程,將兩個.m檔案設定成-fno-objc-arc
 */
@interface RootViewController : UIViewController
<AsyncSocketDelegate>

//  RootViewController.m
#import "RootViewController.h"

@interface RootViewController ()
{
    //用戶端的socket,用於與伺服器進行資料通訊
    AsyncSocket *_clientSocket;
}
@end

@implementation RootViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    UIButton *connectBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [connectBtn setTitle:@"connect" forState:UIControlStateNormal];
    [connectBtn setFrame:CGRectMake(10,30,300,40)];
    [connectBtn addTarget:self action:@selector(connectBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:connectBtn];
    
    UIButton *sendBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [sendBtn setTitle:@"send" forState:UIControlStateNormal];
    [sendBtn setFrame:CGRectMake(10,80,300,40)];
    [sendBtn addTarget:self action:@selector(sendData) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:sendBtn];
    
    // Do any additional setup after loading the view.
}
//向已經串連成功的伺服器發送資料
- (void)sendData{
    NSString *sendMsg = @"hello server!";
    NSData *data = [sendMsg dataUsingEncoding:NSUTF8StringEncoding];
    //writeData 要發送的資料, -1不限時發送,tag 用於標識當前操作
    [_clientSocket writeData:data withTimeout:-1 tag:0];
}

- (void)connectBtnClicked{
    //如果對象不存在,則建立
    if (!_clientSocket) {
        //初始化並設定代理
        _clientSocket = [[AsyncSocket alloc] initWithDelegate:self];
    }
    //isConnected 是否與伺服器進行了聯絡
    if ([_clientSocket isConnected]) {
        [_clientSocket disconnect];//如果串連了,則中斷連線
    }
    //通過ip+連接埠,串連到指定的伺服器
    //[_clientSocket connectToHost:<#(NSString *)#> onPort:<#(UInt16)#> error:<#(NSError *__autoreleasing *)#>]
    //ip地址為原生,因為伺服器也是在同一台電腦裡建立

    //連接埠 任意四位元字
    //connectToHost 和onPort 為伺服器的ip地址和連接埠
    //-1 不限時串連
    [_clientSocket connectToHost:@"自己的ip地址" onPort:5678 withTimeout:-1 error:nil];
}

#pragma mark - asyncsocket delegate
//如果與伺服器串連成功,則調用此方法
- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port{
    NSLog(@"did connected!");
}
//資料發送完成,調用此方法
- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag{
    NSLog(@"send data!");
}


 

TcpServer 服務端:  需要匯入AsyncSocket 第三方

#import "AppDelegate.h"
@implementation AppDelegate{
    //服務端的socket對象,負責監聽是否有用戶端連入
    AsyncSocket *_serverSocket;
    //用於儲存socket對象
    NSMutableArray *_socketArray;
   
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    // Insert code here to initialize your application
    _socketArray = [[NSMutableArray alloc] init];
    //執行createServer方法
    //讓self 0.2秒之後執行 createServer
    [self performSelector:@selector(createServer) withObject:nil afterDelay:0.2];
    
}
- (void)createServer{
    //初始化
    _serverSocket = [[AsyncSocket alloc] initWithDelegate:self];
    //監聽自己的ip和連接埠是否有用戶端連入
    //[_serverSocket acceptOnInterface:@"自己的ip地址" port:5678 error:nil];
    //ip地址可以預設
    [_serverSocket acceptOnPort:5678 error:nil];
}
#pragma mark - async Socket delegate
//一旦有用戶端連入,會調用此方法
//newSocket 服務端建立的socket對象,用於與用戶端進行後續的資料互動
- (void)onSocket:(AsyncSocket *)sock didAcceptNewSocket:(AsyncSocket *)newSocket{
    NSLog(@"accept socket!");
    //需要將newSocketObject Storage Service起來,否則,該對象會被自動釋放
    [_socketArray addObject:newSocket];
    //newSocket對象用於監聽已經接入的用戶端是否會發來訊息
    //不限時監聽是否有資料發送過來
   [newSocket readDataWithTimeout:-1 tag:100];
}
//接收到用戶端的資料時,會觸發此方法
//data為用戶端的資料
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
    NSString *msg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"receive data:%@",msg);
    //一旦接收到了資料,上一次監聽失效,需要繼續監聽
    [sock readDataWithTimeout:-1 tag:101];
}
//當用戶端與服務端即將中斷連線時,觸發此方法
- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err{
    NSLog(@"will disconnect!");
}
//已經中斷連線
- (void)onSocketDidDisconnect:(AsyncSocket *)sock{
    NSLog(@"did disconnect!");
}

 

TCP移動端跟伺服器資料互動

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.