11.5 给WebSocket加密
上面的应用程序虽然工作的很好,但是在网络上收发消息存在很大的安全隐患,所以有必要对消息进行加密。添加这样一个加密的功能一般比较复杂,需要对代码有较大的改动。但是使用Netty就可以很容易的添加这样的功能,只需要将SslHandler加入到ChannelPipeline中就可以了。实际上还需要添加SslContext,但这不在本例子范围内。
首先我们创建一个用于添加加密Handler的handler初始化类,看下面代码:
[java] view plaincopy
- package netty.in.action;
- import io.netty.channel.Channel;
- import io.netty.channel.group.ChannelGroup;
- import io.netty.handler.ssl.SslHandler;
- import javax.net.ssl.SSLContext;
- import javax.net.ssl.SSLEngine;
- public class SecureChatServerIntializer extends ChatServerInitializer {
- private final SSLContext context;
- public SecureChatServerIntializer(ChannelGroup group,SSLContext context) {
- super(group);
- this.context = context;
- }
- @Override
- protected void initChannel(Channel ch) throws Exception {
- super.initChannel(ch);
- SSLEngine engine = context.createSSLEngine();
- engine.setUseClientMode(false);
- ch.pipeline().addFirst(new SslHandler(engine));
- }
}
最后我们创建一个用于引导配置的类,看下面代码:
[java] view plaincopy
- package netty.in.action;
- import io.netty.channel.Channel;
- import io.netty.channel.ChannelFuture;
- import io.netty.channel.ChannelInitializer;
- import io.netty.channel.group.ChannelGroup;
- import java.net.InetSocketAddress;
- import javax.net.ssl.SSLContext;
- /**
- @author c.k
- */
- public class SecureChatServer extends ChatServer {
- private final SSLContext context;
- public SecureChatServer(SSLContext context) {
- this.context = context;
- }
- @Override
- protected ChannelInitializer<Channel> createInitializer(ChannelGroup group) {
- return new SecureChatServerIntializer(group, context);
- }
- /**
- 获取SSLContext需要相关的keystore文件,这里没有 关于HTTPS可以查阅相关资料,这里只介绍在Netty中如何使用
- @return
- */
- private static SSLContext getSslContext() {
- return null;
- }
- public static void main(String[] args) {
- SSLContext context = getSslContext();
- final SecureChatServer server = new SecureChatServer(context);
- ChannelFuture future = server.start(new InetSocketAddress(4096));
- Runtime.getRuntime().addShutdownHook(new Thread() {
- @Override
- public void run() {
- server.destroy();
- }
- });
- future.channel().closeFuture().syncUninterruptibly();
- }
- }