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