最近项目需要使用netty做中转服务器,同时支持两种不同协议的客户端,经过几天查询资料终于找到合适的方案了,同时感谢Netty权威指南及论坛问答,开始贴代码
客户端1==》socket
public class Bluetooth implements Runnable {
//蓝牙
private int port;
@Override
public void run() {
System.out.println("--------进入蓝牙---------");
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workGroup);
b.channel(NioServerSocketChannel.class);
b.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
System.out.println("chhhh"+ch.id());
// 注册handler
/*ch.pipeline().addLast("http-codec", new HttpServerCodec());
ch.pipeline().addLast("aggregator", new HttpObjectAggregator(65536));
ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler());*/
ch.pipeline().addLast(new SimpleServerHandler());
}
});
// b.childHandler(new ChannelFilter());
System.out.println("平台监听开启....");
Channel ch = b.bind(5500).sync().channel();
ch.closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
}finally{
//优雅的退出程序
bossGroup.shutdownGracefully();
workGroup.shutdownGracefully();
}
}
}
客户端2==》http
public class Myweb implements Runnable {
//Myweb
private int port;
@Override
public void run() {
System.out.println("--------进入web---------");
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workGroup);
b.channel(NioServerSocketChannel.class);
b.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel e) throws Exception {
System.out.println("chhhh"+e.id());
e.pipeline().addLast("http-codec", new HttpServerCodec());
e.pipeline().addLast("aggregator", new HttpObjectAggregator(65536));
e.pipeline().addLast("http-chunked", new ChunkedWriteHandler());
e.pipeline().addLast(new SimpleServerHandler());
}
});
// b.childHandler(new ChannelFilter());
System.out.println("平台监听开启....");
Channel ch = b.bind(8888).sync().channel();
ch.closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
}finally{
//优雅的退出程序
bossGroup.shutdownGracefully();
workGroup.shutdownGracefully();
}
}
}
main==>开启两个监听线程
public class main {
private int port;
public main(int port) {
this.port = port;
}
public void run() throws Exception {
}
public static void main(String[] args) throws Exception {
// new main(5500).run();
Bluetooth bluetooth = new Bluetooth();
Myweb myweb = new Myweb();
Thread th1 = new Thread(bluetooth);
Thread th2 = new Thread(myweb);
th1.start();
th2.start();
}
}
Handler代码就不贴了,网上很多,主要是通过多线程分别使用不同编解码器,
对不同客户端的协议进行解析。同时将Chnnel通道保存在Map集合中,两个线程可共享这个Chnnel。