你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> iOS AsyncSocket 與 Java Netty 的簡單socket使用

iOS AsyncSocket 與 Java Netty 的簡單socket使用

編輯:IOS開發綜合
這兩天簡單看了一下Netty框架的東西。 Netty提供異步的、事件驅動的網絡應用程序框架和工具,用以快速開發高性能、高可靠性的網絡服務器和客戶端程序。也就是說,Netty 是一個基於NIO的客戶,服務器端編程框架,使用Netty 可以確保你快速和簡單的開發出一個網絡應用,例如實現了某種協議的客戶,服務端應用。Netty相當簡化和流線化了網絡應用的編程開發過程,例如,TCP和UDP的socket服務開發。   所以參照官方介紹   AsyncSocket 是基於CFSocket與CFStream封裝的TCP/IP socket的網絡庫,它提供了異步操作,本地cocoa類的delegate支持。主要關鍵特新如下: 1.隊列的可選超時的非阻塞的讀和寫。比如:你告訴它讀寫的內容,他將在完成的時候通知你. 2.socket的自動接收。如果你告訴它接受連接,它將為每個連接建立新的實例供你調用。你也可以選擇立即斷開連接。 3.支持Delegate,delegate方法中包含錯誤、連接,接收,完整的讀寫、進度、以及斷開連接。 4.不基於線程(thread)而基於Run-loop.雖然你可以主線程或者子線程中可以使用,但是木有必要。它使用NSRunLoop異步調用委托的方法。委托方法包括一個socket參數,允許區分多個實例。 5.自包裝在一個類中。你不需要操作流或Socket。它會自己處理。 6.支持基於IPv4、IPv6的TCP流。   github地址:   當然首先第一步就是下載和安裝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

 

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