簡書地址圖文更清晰: https://www.jianshu.com/p/f455814f3c40
1、新建maven工程
2、引入maven依賴
<dependencies> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.49.Final</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.68</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.6.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build>
3、定義消息體MsgBody
public class MsgBody { //發送人名稱 private String sendUserName; private String msg; public String getSendUserName() { return sendUserName; } public void setSendUserName(String sendUserName) { this.sendUserName = sendUserName; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
4、新建服務器端的NettyServer和ServerHandler
/** * netty的服務器 * @Author: yeyongjian * @Date: 2020-05-03 23:34 */ public class NettyServer { private int port; public NettyServer(int port) { this.port = port; bind(); } private void bind() { EventLoopGroup boss = new NioEventLoopGroup(); EventLoopGroup worker = new NioEventLoopGroup(); try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(boss, worker); bootstrap.channel(NioServerSocketChannel.class); bootstrap.option(ChannelOption.SO_BACKLOG, 1024); // 連接數 bootstrap.option(ChannelOption.TCP_NODELAY, true); // 不延遲,消息立即發送 bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true); // 長連接 bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel){ ChannelPipeline p = socketChannel.pipeline(); ServerHandler serverHandler = new ServerHandler(); p.addLast(serverHandler);// 添加NettyServerHandler,用來處理Server端接收和處理消息的邏輯 } }); ChannelFuture channelFuture = bootstrap.bind(port).sync(); if (channelFuture.isSuccess()) { System.err.println("啟動Netty服務成功,端口號:" + this.port); } // 關閉連接 channelFuture.channel().closeFuture().sync(); } catch (Exception e) { System.err.println("啟動Netty服務異常,異常信息:" + e.getMessage()); e.printStackTrace(); } finally { boss.shutdownGracefully(); worker.shutdownGracefully(); } } public static void main(String[] args) throws InterruptedException { new NettyServer(10086); } }
import com.alibaba.fastjson.JSONObject; import com.eujian.im.MsgBody; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelId; import io.netty.channel.SimpleChannelInboundHandler; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Map; /** * 服務器的處理器 * @Author: yeyongjian * @Date: 2020-05-03 23:35 */ public class ServerHandler extends SimpleChannelInboundHandler { //連接id與容器的關系 private static Map<String, ChannelHandlerContext> map = new HashMap<>(); @Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) { Channel channel = ctx.channel(); ChannelId id = channel.id(); map.put(id.toString(),ctx); ByteBuf buf = (ByteBuf) msg; String recieved = getMessage(buf); MsgBody msgBody = JSONObject.parseObject(recieved, MsgBody.class); String format = String.format("服務器接收到客戶端消息,發送人:%s,發送信息:%s", msgBody.getSendUserName(), msgBody.getMsg()); System.err.println(format); map.forEach((k,v)->{ try { if(id.toString().equals(k)){ return; } MsgBody sendMsgBody = new MsgBody(); sendMsgBody.setSendUserName(msgBody.getSendUserName()); sendMsgBody.setMsg(msgBody.getMsg()); v.writeAndFlush(getSendByteBuf(JSONObject.toJSONString(sendMsgBody)))