使用最新Netty实现一个简单的聊天程序

版权声明:http://blog.csdn.net/anxpp https://blog.csdn.net/anxpp/article/details/52139155

原文出自:http://blog.csdn.net/anxpp/article/details/52139155,转载请注明出处,想想!

1、概述

    Netty是由JBOSS提供的一个java开源框架。Netty提供异步的、事件驱动的网络应用程序框架和工具,用以快速开发高性能、高可靠性的网络服务器和客户端程序。

    官网:http://netty.io/

    目前最新的是版本是4.1.4(5.x版本官网已经弃用,不推荐使用)。

    Netty4.x同时也是原生支持Android的,所以后面的程序,放到android上也是可以正常运行的(亲测)。

    项目如果使用Maven开发,直接添加以下依赖即可:

  1. <dependency>
  2. <groupId>io.netty</groupId>
  3. <artifactId>netty-all</artifactId>
  4. <version>4.1.4.Final</version>
  5. </dependency>

2、实现服务端

    首先是消息处理类ServerHandler

  1. package com.anxpp.im.server.handler;
  2. import io.netty.channel.ChannelHandler;
  3. import io.netty.channel.ChannelHandlerContext;
  4. import io.netty.channel.ChannelInboundHandlerAdapter;
  5. import java.io.IOException;
  6. import com.anxpp.im.common.IMMessage;
  7. import com.anxpp.im.common.OnlineUser;
  8. import com.anxpp.im.server.config.BaseConfig;
  9. @ChannelHandler.Sharable
  10. public class ServerHandler extends ChannelInboundHandlerAdapter implements BaseConfig{
  11. private ChannelHandlerContext ctx;
  12. @Override
  13. public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
  14. System.err.println("服务端Handler创建...");
  15. super.handlerAdded(ctx);
  16. }
  17. @Override
  18. public void channelInactive(ChannelHandlerContext ctx) throws Exception {
  19. System.err.println("channelInactive");
  20. super.channelInactive(ctx);
  21. }
  22. /**
  23. * tcp链路建立成功后调用
  24. */
  25. @Override
  26. public void channelActive(ChannelHandlerContext ctx) throws Exception {
  27. this.ctx = ctx;
  28. System.err.println("有客户端连接:"+ctx.channel().remoteAddress().toString());
  29. }
  30. /**
  31. * 发送消息
  32. */
  33. public boolean sendMsg(IMMessage msg) throws IOException {
  34. System.err.println("服务器推送消息:"+msg);
  35. ctx.writeAndFlush(msg);
  36. return msg.getMsg().equals("q") ? false : true;
  37. }
  38. @Override
  39. public void channelRead(ChannelHandlerContext ctx, Object msg) throws IOException {
  40. System.err.println("服务器接收到消息:"+msg);
  41. IMMessage message = (IMMessage)msg;
  42. if(OnlineUser.get(message.getReceiveId())==null){
  43. OnlineUser.put(message.getUid(), ctx);
  44. }
  45. ChannelHandlerContext c = OnlineUser.get(message.getReceiveId());
  46. if(c==null){
  47. message.setMsg("对方不在线!");
  48. OnlineUser.get(message.getUid()).writeAndFlush(message);
  49. }
  50. else
  51. c.writeAndFlush(message);
  52. }
  53. /**
  54. * 异常处理
  55. */
  56. @Override
  57. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
  58. System.err.println("与客户端断开连接:"+cause.getMessage());
  59. cause.printStackTrace();
  60. ctx.close();
  61. }
  62. }

    接收客户端连接,如果客户端没有连接过,就保存ChannelHandlerContext到Map中用于发送消息。然后判断消息接收方是否在线,若在线就直接发送消息,没有在线就返回“对方不在线”。当然,可以将消息发送者和消息接收者ID设置为相同就能仅开一个客户端自己跟自己聊天(类似Echo Server)。

    服务器程序Server

  1. package com.anxpp.im.server;
  2. import io.netty.bootstrap.ServerBootstrap;
  3. import io.netty.channel.ChannelFuture;
  4. import io.netty.channel.ChannelInitializer;
  5. import io.netty.channel.ChannelOption;
  6. import io.netty.channel.EventLoopGroup;
  7. import io.netty.channel.nio.NioEventLoopGroup;
  8. import io.netty.channel.socket.SocketChannel;
  9. import io.netty.channel.socket.nio.NioServerSocketChannel;
  10. import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
  11. import io.netty.handler.codec.LengthFieldPrepender;
  12. import java.io.IOException;
  13. import java.util.Scanner;
  14. import com.anxpp.im.common.IMMessage;
  15. import com.anxpp.im.common.MsgPackDecode;
  16. import com.anxpp.im.common.MsgPackEncode;
  17. import com.anxpp.im.server.config.BaseConfig;
  18. import com.anxpp.im.server.handler.ServerHandler;
  19. public class Server implements Runnable,BaseConfig{
  20. ServerHandler serverHandler = new ServerHandler();
  21. public static void main(String[] args) throws IOException{
  22. new Server().start();
  23. }
  24. public void start() throws IOException{
  25. new Thread(this).start();
  26. runServerCMD();
  27. }
  28. /**启动服务端控制台
  29. * @throws IOException */
  30. private void runServerCMD() throws IOException {
  31. //服务端主动推送消息
  32. int toID = 1;
  33. IMMessage message = new IMMessage(
  34. APP_IM,
  35. CLIENT_VERSION,
  36. SERVER_ID,
  37. TYPE_MSG_TEXT,
  38. toID,
  39. MSG_EMPTY);
  40. @SuppressWarnings("resource")
  41. Scanner scanner = new Scanner(System.in);
  42. do{
  43. message.setMsg(scanner.nextLine());
  44. }
  45. while (serverHandler.sendMsg(message));
  46. }
  47. public void run() {
  48. EventLoopGroup bossGroup = new NioEventLoopGroup();
  49. EventLoopGroup workerGroup = new NioEventLoopGroup();
  50. try {
  51. ServerBootstrap b = new ServerBootstrap();
  52. b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 1024)
  53. // .childOption(ChannelOption.SO_KEEPALIVE, true)
  54. .childHandler(new ChannelInitializer<SocketChannel>() {
  55. @Override
  56. public void initChannel(SocketChannel ch) throws Exception {
  57. ch.pipeline().addLast("frameDecoder", new LengthFieldBasedFrameDecoder(65536, 0, 2, 0, 2));
  58. ch.pipeline().addLast("msgpack decoder",new MsgPackDecode());
  59. ch.pipeline().addLast("frameEncoder", new LengthFieldPrepender(2));
  60. ch.pipeline().addLast("msgpack encoder",new MsgPackEncode());
  61. ch.pipeline().addLast(serverHandler);
  62. }
  63. });
  64. ChannelFuture f = b.bind(SERVER_PORT).sync();
  65. f.channel().closeFuture().sync();
  66. } catch (InterruptedException e) {
  67. e.printStackTrace();
  68. } finally {
  69. workerGroup.shutdownGracefully();
  70. bossGroup.shutdownGracefully();
  71. }
  72. }
  73. }

    有几点要说明一下:

    1、runServerCMD方法用于开启控制台输入,可以给指定ID的客户端推送消息(推送服务器就是这么来的)。

    2、MsgPackEncode和MsgPackDecode用于消息的编解码。使用的是MessagePack(编码后字节流特小,编解码速度超快,同时几乎支持所有主流编程语言,详情见官网:http://msgpack.org/)。这样我们可以随意编写实体用于发送消息,他们的代码将在后面给出。

    3、LengthFieldBasedFrameDecoder和LengthFieldPrepender:因为TCP底层传输数据时是不了解上层业务的,所以传输消息的时候很容易造成粘包/半包的情况(一条完整的消息被拆开或者完整或者不完整的多条消息被合并到一起发送、接收),这两个工具就是Netty提供的消息编码工具,2表示消息长度(不是正真的长度为2,是2个字节)。

3、实现客户端

    客户端消息处理类ClientHandler

  1. package com.anxpp.im.client.handler;
  2. import io.netty.channel.ChannelHandlerContext;
  3. import io.netty.channel.ChannelInboundHandlerAdapter;
  4. import java.io.IOException;
  5. import com.anxpp.im.client.Client;
  6. import com.anxpp.im.client.config.BaseConfig;
  7. import com.anxpp.im.common.IMMessage;
  8. public class ClientHandler extends ChannelInboundHandlerAdapter implements BaseConfig {
  9. private ChannelHandlerContext ctx;
  10. /**
  11. * tcp链路简历成功后调用
  12. */
  13. @Override
  14. public void channelActive(ChannelHandlerContext ctx) throws Exception {
  15. System.out.println("成功连接服务器");
  16. this.ctx = ctx;
  17. IMMessage message = new IMMessage(
  18. APP_IM,
  19. CLIENT_VERSION,
  20. Client.UID,
  21. TYPE_CONNECT,
  22. SERVER_ID,
  23. MSG_EMPTY);
  24. sendMsg(message);
  25. }
  26. /**
  27. * 发送消息
  28. * @param msg
  29. * @return
  30. * @throws IOException
  31. */
  32. public boolean sendMsg(IMMessage msg) throws IOException {
  33. System.out.println("client:" + msg);
  34. ctx.channel().writeAndFlush(msg);
  35. return msg.getMsg().equals("q") ? false : true;
  36. }
  37. /**
  38. * 收到消息后调用
  39. * @throws IOException
  40. */
  41. @Override
  42. public void channelRead(ChannelHandlerContext ctx, Object msg) throws IOException {
  43. IMMessage m = (IMMessage)msg;
  44. System.out.println(m.getUid() + ":" + m.getMsg());
  45. }
  46. /**
  47. * 发生异常时调用
  48. */
  49. @Override
  50. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
  51. System.err.println("与服务器断开连接:"+cause.getMessage());
  52. ctx.close();
  53. }
  54. }

    代码跟服务端差不多,也就不多说了。

    客户端Client

  1. package com.anxpp.im.client;
  2. import io.netty.bootstrap.Bootstrap;
  3. import io.netty.channel.ChannelFuture;
  4. import io.netty.channel.ChannelInitializer;
  5. import io.netty.channel.ChannelOption;
  6. import io.netty.channel.EventLoopGroup;
  7. import io.netty.channel.nio.NioEventLoopGroup;
  8. import io.netty.channel.socket.SocketChannel;
  9. import io.netty.channel.socket.nio.NioSocketChannel;
  10. import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
  11. import io.netty.handler.codec.LengthFieldPrepender;
  12. import java.io.IOException;
  13. import java.util.Scanner;
  14. import com.anxpp.im.client.config.BaseConfig;
  15. import com.anxpp.im.client.handler.ClientHandler;
  16. import com.anxpp.im.common.IMMessage;
  17. import com.anxpp.im.common.MsgPackDecode;
  18. import com.anxpp.im.common.MsgPackEncode;
  19. public class Client implements Runnable,BaseConfig {
  20. public static int UID = 8888;
  21. private ClientHandler clientHandler = new ClientHandler();
  22. public static void main(String[] args) throws IOException{
  23. new Client().start();
  24. }
  25. public void start() throws IOException{
  26. new Thread(this).start();
  27. runServerCMD();
  28. }
  29. public void sendMsg(IMMessage msg) throws IOException {
  30. clientHandler.sendMsg(msg);
  31. }
  32. /**启动客户端控制台*/
  33. private void runServerCMD() throws IOException {
  34. IMMessage message = new IMMessage(
  35. APP_IM,
  36. CLIENT_VERSION,
  37. UID,
  38. TYPE_MSG_TEXT,
  39. UID,
  40. MSG_EMPTY);
  41. @SuppressWarnings("resource")
  42. Scanner scanner = new Scanner(System.in);
  43. do{
  44. message.setMsg(scanner.nextLine());
  45. }
  46. while (clientHandler.sendMsg(message));
  47. }
  48. @Override
  49. public void run() {
  50. EventLoopGroup workerGroup = new NioEventLoopGroup();
  51. try {
  52. Bootstrap b = new Bootstrap();
  53. b.group(workerGroup);
  54. b.channel(NioSocketChannel.class);
  55. b.option(ChannelOption.SO_KEEPALIVE, true);
  56. b.handler(new ChannelInitializer<SocketChannel>() {
  57. @Override
  58. public void initChannel(SocketChannel ch) throws Exception {
  59. ch.pipeline().addLast("frameDecoder", new LengthFieldBasedFrameDecoder(65536, 0, 2, 0, 2));
  60. ch.pipeline().addLast("msgpack decoder",new MsgPackDecode());
  61. ch.pipeline().addLast("frameEncoder", new LengthFieldPrepender(2));
  62. ch.pipeline().addLast("msgpack encoder",new MsgPackEncode());
  63. ch.pipeline().addLast(clientHandler);
  64. }
  65. });
  66. ChannelFuture f = b.connect(SERVER_HOST, SERVER_PORT).sync();
  67. f.channel().closeFuture().sync();
  68. } catch (InterruptedException e) {
  69. e.printStackTrace();
  70. } finally {
  71. workerGroup.shutdownGracefully();
  72. }
  73. }
  74. }

    代码依然跟服务端大同小异,不多说。

4、编解码实现

    前面已经简单的介绍了MessagePack了,这里直接给代码。

    maven依赖是这样的:

  1. <dependency>
  2. <groupId>org.msgpack</groupId>
  3. <artifactId>msgpack</artifactId>
  4. <version>0.6.12</version>
  5. </dependency>

    也可以使用core包,不过编解码更复杂,但是速度会略快一点点。

    编码MsgPackEncode

  1. package com.anxpp.im.common;
  2. import io.netty.buffer.ByteBuf;
  3. import io.netty.channel.ChannelHandlerContext;
  4. import io.netty.handler.codec.MessageToByteEncoder;
  5. import java.io.IOException;
  6. import org.msgpack.MessagePack;
  7. /**
  8. * 编码工具
  9. */
  10. public class MsgPackEncode extends MessageToByteEncoder<IMMessage>{
  11. @Override
  12. protected void encode(ChannelHandlerContext ctx, IMMessage msg, ByteBuf out) throws IOException {
  13. out.writeBytes(new MessagePack().write(msg));
  14. }
  15. }

    解码MsgPackDecode

  1. package com.anxpp.im.common;
  2. import io.netty.buffer.ByteBuf;
  3. import io.netty.channel.ChannelHandlerContext;
  4. import io.netty.handler.codec.MessageToMessageDecoder;
  5. import java.util.List;
  6. import org.msgpack.MessagePack;
  7. /**
  8. * 解码工具
  9. */
  10. public class MsgPackDecode extends MessageToMessageDecoder<ByteBuf>{
  11. @Override
  12. protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
  13. final int length = msg.readableBytes();
  14. final byte[] array = new byte[length];
  15. msg.getBytes(msg.readerIndex(), array, 0, length);
  16. out.add(new MessagePack().read(array,IMMessage.class));
  17. }
  18. }

5、公共代码:

    消息类IMMessage

  1. package com.anxpp.im.common;
  2. public class IMMessage {
  3. //应用ID
  4. private byte appId;
  5. //版本号
  6. private int version;
  7. //用户ID
  8. private int uid;
  9. //消息类型 0:登陆 1:文字消息
  10. private byte msgType;
  11. //接收方
  12. private int receiveId;
  13. //消息内容
  14. private String msg;
  15. public IMMessage() {}
  16. /**
  17. * 构造方法
  18. * @param appId 应用通道
  19. * @param version 应用版本
  20. * @param uid 用户ID
  21. * @param msgType 消息类型
  22. * @param receiveId 消息接收者
  23. * @param msg 消息内容
  24. */
  25. public IMMessage(byte appId, int version, int uid, byte msgType, int receiveId, String msg) {
  26. this.appId = appId;
  27. this.version = version;
  28. this.uid = uid;
  29. this.msgType = msgType;
  30. this.receiveId = receiveId;
  31. this.msg = msg;
  32. }
  33. public byte getAppId() {
  34. return appId;
  35. }
  36. public void setAppId(byte appId) {
  37. this.appId = appId;
  38. }
  39. public int getVersion() {
  40. return version;
  41. }
  42. public void setVersion(int version) {
  43. this.version = version;
  44. }
  45. public int getUid() {
  46. return uid;
  47. }
  48. public void setUid(int uid) {
  49. this.uid = uid;
  50. }
  51. public String getMsg() {
  52. return msg;
  53. }
  54. public void setMsg(String msg) {
  55. this.msg = msg;
  56. }
  57. public byte getMsgType() {
  58. return msgType;
  59. }
  60. public void setMsgType(byte msgType) {
  61. this.msgType = msgType;
  62. }
  63. public int getReceiveId() {
  64. return receiveId;
  65. }
  66. public void setReceiveId(int receiveId) {
  67. this.receiveId = receiveId;
  68. }
  69. @Override
  70. public String toString() {
  71. return "appId:"+this.appId+",version:"+this.version+",uid:"+this.uid+",msgType:"+this.msgType+",receiveId:"+this.receiveId+",msg:"+this.msg;
  72. }
  73. }

    在线用户OnlineUser

  1. package com.anxpp.im.common;
  2. import io.netty.channel.ChannelHandlerContext;
  3. import java.util.HashMap;
  4. /**
  5. * 在线用户表
  6. * @author Administrator
  7. *
  8. */
  9. public class OnlineUser {
  10. //用户表
  11. private static HashMap<Integer, ChannelHandlerContext> onlineUser = new HashMap<Integer, ChannelHandlerContext>();
  12. public static void put(Integer uid, ChannelHandlerContext uchc){
  13. onlineUser.put(uid, uchc);
  14. }
  15. public static void remove(Integer uid){
  16. onlineUser.remove(uid);
  17. }
  18. public static ChannelHandlerContext get(Integer uid){
  19. return onlineUser.get(uid);
  20. }
  21. }

    公共配置IMConfig

  1. package com.anxpp.im.common;
  2. public interface IMConfig {
  3. /**客户端配置*/
  4. int CLIENT_VERSION = 1; //版本号
  5. /**服务端配置*/
  6. String SERVER_HOST = "127.0.0.1"; //服务器IP
  7. int SERVER_PORT = 9090; //服务器端口
  8. /**消息相关*/
  9. int SERVER_ID = 0; //表示服务器消息
  10. byte APP_IM = 1; //即时通信应用ID为1
  11. byte TYPE_CONNECT = 0; //连接后第一次消息确认建立连接和发送认证信息
  12. byte TYPE_MSG_TEXT = 1; //文本消息
  13. String MSG_EMPTY = ""; //空消息
  14. }

6、完成

    此时就可以运行服务端可客户端测试了,本人亲测可用的。

    我的整个工程是使用Maven依赖的:

10

    目前已经将客户端部分移动到Android下使用了,不过功能还很简单,等完成后在放到Github上。

    时间真的是不够用啊,想想有个BUG调了我大半天全都是泪(最后还是强大的Google帮我解决了)。

    代码非常简陋,只是简单的实现了一下,解释得也很少,如果哪里不清楚,再一起探讨吧...

阅读更多 登录后自动展开
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页