socket 收不到netty客户端消息_Netty开发 —— 首个demo学习
生活随笔
收集整理的這篇文章主要介紹了
socket 收不到netty客户端消息_Netty开发 —— 首个demo学习
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
1. 編寫服務(wù)端代碼
編寫業(yè)務(wù)邏輯:讀取到客戶端的消息時候,打印客戶端消息,并給客戶端回復一條消息
import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; 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 DemoNettyServer {public void bind(int port) throws Exception {// 主線程組EventLoopGroup bossGroup = new NioEventLoopGroup();// 從線程組EventLoopGroup workerGroup = new NioEventLoopGroup();try {// netty服務(wù)器啟動類ServerBootstrap serverBootstrap = new ServerBootstrap();serverBootstrap.group(bossGroup, workerGroup) //綁定兩個線程組// 用于構(gòu)造socketchannel工廠.channel(NioServerSocketChannel.class) //指定NIO的模式.childHandler(new ChannelInitializer<SocketChannel>() { // 子處理器,用于處理workerGroupprotected void initChannel(SocketChannel socketChannel) throws Exception {socketChannel.pipeline().addLast(new DemoNettyServerHandler());}});// 啟動server,綁定端口ChannelFuture channelFuture = serverBootstrap.bind(8088).sync();System.out.println("server start");// 監(jiān)聽關(guān)閉的channel,等待服務(wù)器 socket 關(guān)閉 。設(shè)置位同步方式channelFuture.channel().closeFuture().sync();System.out.println("server close");} finally {//退出線程組bossGroup.shutdownGracefully();workerGroup.shutdownGracefully();}}public static void main(String[] args) throws Exception {int port = 8080;new DemoNettyServer().bind(port);}} import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter;public class DemoNettyServerHandler extends ChannelInboundHandlerAdapter {/*** 本方法用于讀取客戶端發(fā)送的信息*/@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {System.out.println("收到來自客服端的一條消息");ByteBuf result = (ByteBuf) msg;byte[] bytesMsg = new byte[result.readableBytes()];// msg中存儲的是ByteBuf類型的數(shù)據(jù),把數(shù)據(jù)讀取到byte[]中result.readBytes(bytesMsg);String resultStr = new String(bytesMsg);// 接收并打印客戶端的信息System.out.println("客服端內(nèi)容:" + resultStr);// 釋放資源,這行很關(guān)鍵result.release();// 向客戶端發(fā)送消息String response = "我是server,我已經(jīng)收到你的消息: " + resultStr;// 在當前場景下,發(fā)送的數(shù)據(jù)必須轉(zhuǎn)換成ByteBuf數(shù)組ByteBuf encoded = ctx.alloc().buffer(4 * response.length());encoded.writeBytes(response.getBytes());ctx.write(encoded);ctx.flush();}/*** 本方法用作處理異常*/@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {// 當出現(xiàn)異常就關(guān)閉連接cause.printStackTrace();ctx.close();}/*** 信息獲取完畢后操作*/@Overridepublic void channelReadComplete(ChannelHandlerContext ctx) throws Exception {ctx.flush();}}2. 編寫客戶端代碼
編寫業(yè)務(wù)邏輯:獲取用戶輸入,連接服務(wù)端,發(fā)送消息,讀取服務(wù)端消息,關(guān)閉連接。
import io.netty.bootstrap.Bootstrap; 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.NioSocketChannel;import java.util.Scanner;public class DemoNettyClient {public void connect(String host, int port) throws Exception {EventLoopGroup worker = new NioEventLoopGroup();try {// 客戶端啟動類程序Bootstrap bootstrap = new Bootstrap();/***EventLoop的組*/bootstrap.group(worker);/*** 用于構(gòu)造socketchannel工廠*/bootstrap.channel(NioSocketChannel.class);/**設(shè)置選項* 參數(shù):Socket的標準參數(shù)(key,value),可自行百度保持呼吸,不要斷氣!* */bootstrap.option(ChannelOption.SO_KEEPALIVE, true);/*** 自定義客戶端Handle(客戶端在這里搞事情)*/bootstrap.handler(new ChannelInitializer<SocketChannel>() {@Overridepublic void initChannel(SocketChannel ch) throws Exception {ch.pipeline().addFirst(new DemoNettyClientHandler());}});/** 開啟客戶端監(jiān)聽,連接到遠程節(jié)點,阻塞等待直到連接完成*/ChannelFuture channelFuture = bootstrap.connect(host, port).sync();/**阻塞等待數(shù)據(jù),直到channel關(guān)閉(客戶端關(guān)閉)*/channelFuture.channel().closeFuture().sync();} finally {worker.shutdownGracefully();}}public static void main(String[] args) throws Exception {while (true){Scanner content = new Scanner(System.in);System.out.print("請輸入您要發(fā)送的內(nèi)容: ");Meesage.CLIENT_MESSAGE = content.nextLine();DemoNettyClient client = new DemoNettyClient();client.connect("127.0.0.1", 8088);}}} import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter;public class DemoNettyClientHandler extends ChannelInboundHandlerAdapter {/*** 服務(wù)端發(fā)過來消息時調(diào)用*/@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {System.out.println("收到來自服務(wù)端的一條消息");ByteBuf result = (ByteBuf) msg;byte[] result1 = new byte[result.readableBytes()];result.readBytes(result1);System.out.println(new String(result1));result.release();//關(guān)閉連接ctx.close();}/*** 異常時調(diào)用*/@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {cause.printStackTrace();ctx.close();}/*** 連接到服務(wù)器調(diào)用*/@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {String msg = Meesage.CLIENT_MESSAGE;ByteBuf encoded = ctx.alloc().buffer(4 * msg.length());encoded.writeBytes(msg.getBytes());ctx.write(encoded);ctx.flush();}} public class Meesage {public static String CLIENT_MESSAGE = "";public static String SERVER_MESSAGE = ""; }3. 結(jié)果分析
客服端截圖(手動輸入消息)服務(wù)端消息總結(jié)
以上是生活随笔為你收集整理的socket 收不到netty客户端消息_Netty开发 —— 首个demo学习的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 服务器管理面板是什么
- 下一篇: 根据id删除localstorage数据