您的位置:首页 > 其它

netty基础入门(二)简单项目搭建

2017-05-21 11:18 423 查看
目的: 搭建简单的服务端和客户端进行通信

服务端搭建

1、新建java project项目,在src下面新建com.nettyServer的package

 nettyServer.java

 package com.nettyServer;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

public class nettyServer {

private static final int BIZGROUPSIZE = Runtime.getRuntime().availableProcessors()*2;
private static final int BIZTHREADSIZE = 100;
private static final EventLoopGroup bossGroup = new NioEventLoopGroup(BIZGROUPSIZE);
private static final EventLoopGroup workerGroup = new NioEventLoopGroup(BIZTHREADSIZE);

public static void main(String args[]){

//服务端
ServerBootstrap serverBootstrap;
//客户端
Bootstrap clientBootstrap;
//客户端通道
Channel clientChannel;
//服务端通道
Channel serverChannel ;

serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workerGroup);
serverBootstrap.channel(NioServerSocketChannel.class);
//添加handler监听服务端的IO动作
// serverBootstrap.handler(new OutHandler());
serverBootstrap.childHandler(new ChannelInitializer<Channel>(){

@Override
protected void initChannel(Channel arg0)
throws Exception {
// TODO Auto-generated method stub
ChannelPipeline pipeline = arg0.pipeline();
pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
pipeline.addLast(new LengthFieldPrepender(4));
pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
//添加handler监听客户端Channel的状态变化
pipeline.addLast(new TcpServerHandler());
}

});
try {
//服务端启动
ChannelFuture cf = serverBootstrap.bind(56560).sync();
System.out.println("服务端启动成功,开始监听端口56560");
// Toast.makeText(getActivity(), "TCP服务器已启动", Toast.LENGTH_SHORT).show();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}
OutHandler.java

package com.nettyServer;

import java.net.SocketAddress;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;

public class OutHandler extends ChannelOutboundHandlerAdapter{
@Override
public void connect(ChannelHandlerContext ctx,
SocketAddress remoteAddress, SocketAddress localAddress,
ChannelPromise promise) throws Exception {
// TODO Auto-generated method stub
super.connect(ctx, remoteAddress, localAddress, promise);
System.out.println("<<<<<<<<<<<<<<< connect server success >>>>>>>>>>>>>>>>");
}

@Override
public void bind(ChannelHandlerContext ctx,
SocketAddress localAddress, ChannelPromise promise)
throws Exception {
// TODO Auto-generated method stub
super.bind(ctx, localAddress, promise);
System.out.println("<<<<<<<<<<<<<<< server bind success >>>>>>>>>>>>>>>>");
}
}
TcpServerhandler.java

package com.nettyServer;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class TcpServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
// TODO Auto-generated method stub
System.out.println("<<<<<<<<<<<<<<<<收到客户端消息 :"+ msg);
ctx.channel().writeAndFlush("<<<<<<<<<<服务端已经接收:" + msg);
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stu
c892
b
System.out.println("通道已经启用>>>>>>>>");
// clientChannel = ctx.channel();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
System.out.println("exception is general");
}
}

客户端搭建: 新建一个java project项目  src下新建 com.nettyClient
nettyClient.java

package com.nettyClient;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

public class nettyClient {

public static void main(String args[]){
EventLoopGroup group = new NioEventLoopGroup();
Bootstrap b = new Bootstrap();
b.group(group);
b.channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true);
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
//添加一个Hanlder用来处理各种Channel状态
pipeline.addLast("handlerIn", new ClientHandler());
//添加一个Handler用来接收监听IO操作的
// pipeline.addLast("handlerOut", new OutHandler());
}
});
ChannelFuture f;
try {
//连接服务端
f = b.connect("127.0.0.1", 56560).sync();
Channel serverChannel = f.channel();
serverChannel.writeAndFlush("<<<<<<<<<<<<<<<<客户端请求连接>>>>>>>>>>>>>>>>");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Outhandler.java 
package com.nettyClient;

import java.net.SocketAddress;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;

public class OutHandler extends ChannelOutboundHandlerAdapter{
@Override
public void connect(ChannelHandlerContext ctx,
SocketAddress remoteAddress, SocketAddress localAddress,
ChannelPromise promise) throws Exception {
// TODO Auto-generated method stub
super.connect(ctx, remoteAddress, localAddress, promise);
System.out.println("<<<<<<<<<<<<<<< connect server success >>>>>>>>>>>>>>>>");
}

@Override
public void bind(ChannelHandlerContext ctx,
SocketAddress localAddress, ChannelPromise promise)
throws Exception {
// TODO Auto-generated method stub
super.bind(ctx, localAddress, promise);
System.out.println("<<<<<<<<<<<<<<< server bind success >>>>>>>>>>>>>>>>");
}
}

ClientHandler.java 
package com.nettyClient;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class ClientHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("<<<<<<<<<客户端收到消息:" + msg);
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
System.out.println("client exception is general");
}
}

引入的jar包,netty-3.5.5-Final.jar
运行项目就会进行服务端与客户端的通信
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: