iOS AsyncSocket 与 Java Netty 的简单socket使用

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地址:https://github.com/roustem/AsyncSocket

第一步:
下载和安装
Netty:使用maven安装Netty

AsyncSocket:使用cocoapods安装

第二步:服务端创建
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

运行结果:

wKiom1Yy5IfxBtr7AAGihZfj6Ak498.jpg
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,390评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,821评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,632评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,170评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,033评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,098评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,511评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,204评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,479评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,572评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,341评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,893评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,171评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,486评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,676评论 2 335

推荐阅读更多精彩内容