11.5 给WebSocket加密

    上面的应用程序虽然工作的很好,但是在网络上收发消息存在很大的安全隐患,所以有必要对消息进行加密。添加这样一个加密的功能一般比较复杂,需要对代码有较大的改动。但是使用Netty就可以很容易的添加这样的功能,只需要将SslHandler加入到ChannelPipeline中就可以了。实际上还需要添加SslContext,但这不在本例子范围内。

    首先我们创建一个用于添加加密Handler的handler初始化类,看下面代码:

[java] view plaincopy

  1. package netty.in.action;
  2. import io.netty.channel.Channel;
  3. import io.netty.channel.group.ChannelGroup;
  4. import io.netty.handler.ssl.SslHandler;
  5. import javax.net.ssl.SSLContext;
  6. import javax.net.ssl.SSLEngine;
  7. public class SecureChatServerIntializer extends ChatServerInitializer {
  8. private final SSLContext context;
  9. public SecureChatServerIntializer(ChannelGroup group,SSLContext context) {
  10. super(group);
  11. this.context = context;
  12. }
  13. @Override
  14. protected void initChannel(Channel ch) throws Exception {
  15. super.initChannel(ch);
  16. SSLEngine engine = context.createSSLEngine();
  17. engine.setUseClientMode(false);
  18. ch.pipeline().addFirst(new SslHandler(engine));
  19. }
  20. }

    最后我们创建一个用于引导配置的类,看下面代码:

[java] view plaincopy

  1. package netty.in.action;
  2. import io.netty.channel.Channel;
  3. import io.netty.channel.ChannelFuture;
  4. import io.netty.channel.ChannelInitializer;
  5. import io.netty.channel.group.ChannelGroup;
  6. import java.net.InetSocketAddress;
  7. import javax.net.ssl.SSLContext;
  8. /**
    • @author c.k
  9. */
  10. public class SecureChatServer extends ChatServer {
  11. private final SSLContext context;
  12. public SecureChatServer(SSLContext context) {
  13. this.context = context;
  14. }
  15. @Override
  16. protected ChannelInitializer<Channel> createInitializer(ChannelGroup group) {
  17. return new SecureChatServerIntializer(group, context);
  18. }
  19. /**
    • 获取SSLContext需要相关的keystore文件,这里没有 关于HTTPS可以查阅相关资料,这里只介绍在Netty中如何使用
    • @return
  20. */
  21. private static SSLContext getSslContext() {
  22. return null;
  23. }
  24. public static void main(String[] args) {
  25. SSLContext context = getSslContext();
  26. final SecureChatServer server = new SecureChatServer(context);
  27. ChannelFuture future = server.start(new InetSocketAddress(4096));
  28. Runtime.getRuntime().addShutdownHook(new Thread() {
  29. @Override
  30. public void run() {
  31. server.destroy();
  32. }
  33. });
  34. future.channel().closeFuture().syncUninterruptibly();
  35. }
  36. }

results matching ""

    No results matching ""