您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS AsyncSocket 與 Java Netty 的 Socket 通訊實作對照

編輯:iOS 開發綜合

這兩天簡單看了一下 Netty 框架。Netty 是一套「非同步、事件驅動」的網路應用程式框架與工具,用於快速開發高效能、高可靠性的網路伺服器與用戶端程式。也就是說,Netty 是一個基於 NIO 的用戶端/伺服器端編程框架,能確保你快速而簡單地開發出網路應用,例如實作某種協議的用戶端或伺服器端。它大幅簡化並 streamlining 了網路應用的開發流程,像 TCP、UDP 的 Socket 開發都因此變得輕鬆許多。

關於 AsyncSocket

對照官方的介紹,AsyncSocket 是基於 CFSocket 與 CFStream 封裝的 TCP/IP Socket 網路庫,提供非同步操作並支援本地 Cocoa 類別的 delegate。它的主要特色如下:

1. 具備「可選超時」的非阻塞讀寫隊列——你只要告訴它讀寫的內容,完成時它就會通知你。

2. Socket 自動接收——當你告訴它接受連線,它就會為每個連線建立新的實例供你呼叫,你也可以選擇立即中斷連線。

3. 完整的 Delegate 支援,delegate 方法涵蓋錯誤、連線、接收、完整讀寫、進度以及中斷連線等狀態。

4. 不基於執行緒(thread)而基於 Run-loop。雖然你可以在主執行緒或子執行緒中使用,但沒有必要;它以 NSRunLoop 非同步呼叫 delegate 方法,delegate 方法帶有 socket 參數,可區分多個實例。

5. 完全封裝在一個類別中,你不需要直接操作串流或 Socket,它會自行處理。

6. 支援 IPv4 與 IPv6 的 TCP 串流。

第一步:下載與安裝

首先当然是下載並安裝 Netty 與 AsyncSocket。

第二步:建立伺服器端

1. HelloServer:

 package com.nettypro.io; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; public class HelloServer { /* * 創建服務端監聽端口 */ private static final int portNumber = 8080; public static void main(String[] args) throws InterruptedException { EventLoopGroup boosGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(boosGroup, workerGroup); bootstrap.channel(NioServerSocketChannel.class); bootstrap.childHandler(new HelloServerInitializer()) .childOption(ChannelOption.SO_KEEPALIVE, true); // (6); //服務器綁定端口監聽 ChannelFuture channelFuture = bootstrap.bind(portNumber).sync(); //監聽服務器關閉監聽 channelFuture.channel().closeFuture().sync(); }finally{ boosGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } }

2. HelloServerInitializer:

 package com.nettypro.io; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.DelimiterBasedFrameDecoder; import io.netty.handler.codec.Delimiters; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; public class HelloServerInitializer extends ChannelInitializer<SocketChannel> { @Override protected void initChannel(SocketChannel arg0) throws Exception { // TODO Auto-generated method stub //ChannelPipeline 可以理解為消息傳送通道 通道一旦建立 持續存在 ChannelPipeline channelPipeline = arg0.pipeline(); //為通道添加功能 //字符串解碼 編碼 channelPipeline.addLast("decoder",new StringDecoder()); channelPipeline.addLast("encoder", new StringEncoder()); //添加自主邏輯 channelPipeline.addLast(new HelloServerHandler()); } }

3. HelloServerHandler:

 package com.nettypro.io; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Scanner; import javax.xml.crypto.Data; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; public class HelloServerHandler extends SimpleChannelInboundHandler<String> { @Override protected void channelRead0(ChannelHandlerContext arg0, String arg1) { // TODO Auto-generated method stub System.out.println(arg0.channel().remoteAddress()+" ----channelRead0"); //收到消息直接打印 System.out.println(arg0.channel().remoteAddress()+" MSG: "+ arg1); //回復消息 Scanner scanner = new Scanner(System.in); String msgString = scanner.nextLine()+"\n"; System.out.println(arg0.channel().remoteAddress()+" msgString: "+ msgString); arg0.writeAndFlush(msgString); } /** * channel被激活時調用 */ @Override public void channelActive(ChannelHandlerContext ctx){ // TODO Auto-generated method stub System.out.println(ctx.channel().remoteAddress()+" ----Acrive"); try { ctx.writeAndFlush("Welcome you to here"+InetAddress.getLocalHost().getHostName()); } catch (UnknownHostException e) { e.printStackTrace(); } } }

第三步:建立用戶端

 #import "ViewController.h" #import <sys/socket.h> #import <netinet/in.h> #import <arpa/inet.h> #import <unistd.h> #import "AsyncSocket.h" @interface ViewController ()<AsyncSocketDelegate> @property (nonatomic, retain) NSTimer *heartTimer; @property (nonatomic, retain) AsyncSocket *ay; @property (strong, nonatomic) IBOutlet UITextField *msgTF; @property (strong, nonatomic) IBOutlet UITextView *showTV; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. self.ay = [[AsyncSocket alloc] initWithDelegate:self]; [self.ay connectToHost:@"localhost" onPort:8080 error:nil]; self.ay.delegate = self; NSString *msg = @"HelloNetty"; [self.ay writeData:[msg dataUsingEncoding:NSUTF8StringEncoding] withTimeout:10.0f tag:101]; [self.ay readDataWithTimeout:-1 tag:0]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (IBAction)sendAction:(UIButton *)sender { if (self.msgTF.text.length != 0) { self.showTV.text = [NSString stringWithFormat:@"%@\n客戶端說:%@",self.showTV.text,self.msgTF.text]; [self.ay writeData:[self.msgTF.text dataUsingEncoding:NSUTF8StringEncoding] withTimeout:10.0f tag:101]; [self.ay readDataWithTimeout:-1 tag:0]; self.msgTF.text = nil; } } #pragma mark #pragma mark --AsyncSocketDelegate-- - (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag { NSString *msg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"msg-----%@",msg); if (self.showTV.text.length == 0) { self.showTV.text = [NSString stringWithFormat:@"服務器說:%@",msg]; } else { self.showTV.text = [NSString stringWithFormat:@"%@\n服務器說:%@",self.showTV.text,msg]; } [self.ay readDataWithTimeout:-1 tag:0]; } - (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag { [self.ay readDataWithTimeout:-1 tag:0]; } -(void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port { NSLog(@"didConnectToHost %@------%d",host,port); [self.ay readDataWithTimeout:-1 tag:0]; } -(void)onSocket:(AsyncSocket *)sock didReadPartialDataOfLength:(NSUInteger)partialLength tag:(long)tag { NSLog(@"Received bytes: %lu",(unsigned long)partialLength); } @end

透過這套組合,我們可以看到伺服器端以 Netty 的事件驅動模型監聽連線、處理訊息,而 iOS 用戶端則以 AsyncSocket 的 delegate 機制完成非同步的連線、讀寫與狀態回饋。兩者在概念上互相呼應,適合用於需要即時、雙向通訊的場景。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved