netty同時支援socket和http
阿新 • • 發佈:2018-11-10
專案需要使用netty做中轉伺服器,同時支援兩種不同協議的客戶端,經過幾天查詢資料終於找到合適的方案了,同時感謝Netty權威指南及論壇問答,開始貼程式碼
客戶端1==》socket
1 public class Bluetooth implements Runnable { 2 //藍芽 3 4 private int port; 5 @Override 6 public void run() { 7 System.out.println("--------進入藍芽---------"); 8 EventLoopGroup bossGroup = newNioEventLoopGroup(); 9 EventLoopGroup workGroup = new NioEventLoopGroup(); 10 try { 11 ServerBootstrap b = new ServerBootstrap(); 12 b.group(bossGroup, workGroup); 13 b.channel(NioServerSocketChannel.class); 14 b.childHandler(new ChannelInitializer<SocketChannel>() {15 @Override 16 public void initChannel(SocketChannel ch) throws Exception { 17 System.out.println("chhhh"+ch.id()); 18 // 註冊handler 19 /*ch.pipeline().addLast("http-codec", new HttpServerCodec());20 ch.pipeline().addLast("aggregator", new HttpObjectAggregator(65536)); 21 ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler());*/ 22 ch.pipeline().addLast(new SimpleServerHandler()); 23 } 24 }); 25 // b.childHandler(new ChannelFilter()); 26 System.out.println("平臺監聽開啟...."); 27 Channel ch = b.bind(5500).sync().channel(); 28 ch.closeFuture().sync(); 29 30 } catch (Exception e) { 31 e.printStackTrace(); 32 }finally{ 33 //優雅的退出程式 34 bossGroup.shutdownGracefully(); 35 workGroup.shutdownGracefully(); 36 } 37 } 38
客戶端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。
參考:https://blog.csdn.net/lmianhuatang/article/details/79675790