directory

introduce

Modify the hosts file locally

Address the screenshot

Modify the screenshots

prompt

First look at all kinds of bugs will not introduce what the meaning of the bug, a lot of introduction

A good plan

introduce

Initializer class plus this

This is the main code

Capture effect

Initialize type full code

Create SslUtil class

The page code

That’s the main thing

Build a detailed framework for my blog

Continuously updated

In the previous setup, SslContext was created only once, eliminating the need to create each call

Start type

Initialization type



introduce

Use localhost 127.0.0.1 and ws for local development

Switching to the server will have to be adjusted, or local access will have to be adjusted

You can modify the hosts file in Windows to add a domain name 127.0.0.1 or the IP address of the peer’s domain

To apply for domain names and develop in the SSL domain, you can configure hosts files first rather than directly configure servers in the domain

Recently put the project out, and other front-end use so need to adjust, from 127 to domain name, make external also accessible, change to find a car bug if you need to see

 

Modify the hosts file locally

System disk: C:\Windows\System32\drivers\etc\hosts

Address the screenshot

Modify the screenshots

prompt

Windows a lot, not so many things are empty, just add it down here

127.0.0.1 Customize the domain name

Or other IP custom domain name

 

 

 

First look at all kinds of bugs will not introduce what the meaning of the bug, a lot of introduction

io.netty.handler.codec.DecoderException: javax.net.ssl.SSLException: Received fatal alert: certificate_unknown

 

Netty URL “WSS / / 192.168.8.109:9999 / ws” is invalid.

 

test.html:39 WebSocket connection to ‘wss://ma.yueduixiang.com:9999/ws’ failed: Error in connection establishment: net::ERR_CONNECTION_CLOSED

 

[nioEventLoopGroup 15:45:17. 585-3-1] WARN io.net ty. Channel. ChannelInitializer – Failed to initialize a channel. Closing: [id: 0x04CB96ee, L:/ 127.0.0.1:9999-r :/127.0.0.1:56833] java.io.ioException: Keystore was tampered with, or password was incorrect at sun.security.provider.JavaKeyStore.engineLoad(JavaKeyStore.java:780) at sun.security.provider.JavaKeyStore$JKS.engineLoad(JavaKeyStore.java:56) at sun.security.provider.KeyStoreDelegator.engineLoad(KeyStoreDelegator.java:224) at sun.security.provider.JavaKeyStore$DualFormatJKS.engineLoad(JavaKeyStore.java:70) at java.security.KeyStore.load(KeyStore.java:1445) at com.superman.nettyim.SslUtil.createSSLContext(SslUtil.java:35) at com.superman.nettyim.IMNettyServerInitialzer.initChannel(IMNettyServerInitialzer.java:44) at com.superman.nettyim.IMNettyServerInitialzer.initChannel(IMNettyServerInitialzer.java:1) at io.netty.channel.ChannelInitializer.initChannel(ChannelInitializer.java:115) at io.netty.channel.ChannelInitializer.handlerAdded(ChannelInitializer.java:107) at io.netty.channel.DefaultChannelPipeline.callHandlerAdded0(DefaultChannelPipeline.java:637) at io.netty.channel.DefaultChannelPipeline.access$000(DefaultChannelPipeline.java:46) at io.netty.channel.DefaultChannelPipeline$PendingHandlerAddedTask.execute(DefaultChannelPipeline.java:1487) at io.netty.channel.DefaultChannelPipeline.callHandlerAddedForAllHandlers(DefaultChannelPipeline.java:1161) at io.netty.channel.DefaultChannelPipeline.invokeHandlerAddedIfNeeded(DefaultChannelPipeline.java:686) at io.netty.channel.AbstractChannel$AbstractUnsafe.register0(AbstractChannel.java:514) at io.netty.channel.AbstractChannel$AbstractUnsafe.access$200(AbstractChannel.java:427) at io.netty.channel.AbstractChannel$AbstractUnsafe$1.run(AbstractChannel.java:486) at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:163) at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:404) at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:474) at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:909) at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) at java.lang.Thread.run(Thread.java:748) Caused by: java.security.UnrecoverableKeyException: Password verification failed at sun.security.provider.JavaKeyStore.engineLoad(JavaKeyStore.java:778) … [nioEventLoopGroup 23 common frames omitted 15:45:17. 602-3-2) WARN io.net ty. Channel. ChannelInitializer – Failed to Initialize a channel. Closing: [id: 0x81b2235f, L:/ 127.0.0.1:9999-r :/127.0.0.1:56837] Java.io.ioException: Keystore was tampered with, or password was incorrect at sun.security.provider.JavaKeyStore.engineLoad(JavaKeyStore.java:780) at sun.security.provider.JavaKeyStore$JKS.engineLoad(JavaKeyStore.java:56) at sun.security.provider.KeyStoreDelegator.engineLoad(KeyStoreDelegator.java:224) at sun.security.provider.JavaKeyStore$DualFormatJKS.engineLoad(JavaKeyStore.java:70) at java.security.KeyStore.load(KeyStore.java:1445) at com.superman.nettyim.SslUtil.createSSLContext(SslUtil.java:35) at com.superman.nettyim.IMNettyServerInitialzer.initChannel(IMNettyServerInitialzer.java:44) at com.superman.nettyim.IMNettyServerInitialzer.initChannel(IMNettyServerInitialzer.java:1) at io.netty.channel.ChannelInitializer.initChannel(ChannelInitializer.java:115) at io.netty.channel.ChannelInitializer.handlerAdded(ChannelInitializer.java:107) at io.netty.channel.DefaultChannelPipeline.callHandlerAdded0(DefaultChannelPipeline.java:637) at io.netty.channel.DefaultChannelPipeline.access$000(DefaultChannelPipeline.java:46) at io.netty.channel.DefaultChannelPipeline$PendingHandlerAddedTask.execute(DefaultChannelPipeline.java:1487) at io.netty.channel.DefaultChannelPipeline.callHandlerAddedForAllHandlers(DefaultChannelPipeline.java:1161) at io.netty.channel.DefaultChannelPipeline.invokeHandlerAddedIfNeeded(DefaultChannelPipeline.java:686) at io.netty.channel.AbstractChannel$AbstractUnsafe.register0(AbstractChannel.java:514) at io.netty.channel.AbstractChannel$AbstractUnsafe.access$200(AbstractChannel.java:427) at io.netty.channel.AbstractChannel$AbstractUnsafe$1.run(AbstractChannel.java:486) at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:163) at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:404) at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:474) at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:909) at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) at java.lang.Thread.run(Thread.java:748) Caused by: java.security.UnrecoverableKeyException: Password verification failed at sun.security.provider.JavaKeyStore.engineLoad(JavaKeyStore.java:778) … 23 common frames omitted

 

 

 

test.html:39 WebSocket connection to ‘wss://ma.yueduixiang.com:9999/ws’ failed: Error in connection establishment: net::ERR_CERT_AUTHORITY_INVALID

 

15:46:33.159 [nioEventLoopGroup-3-1] WARN io.netty.channel.DefaultChannelPipeline – An exceptionCaught() event was fired, and it reached at the tail of the pipeline. It usually means the last handler in the pipeline did not handle the exception.

io.netty.handler.codec.DecoderException: javax.net.ssl.SSLException: Received fatal alert: certificate_unknown

at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:472)

at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:278)

at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362)

at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348)

at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340)

at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1434)

at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362)

at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348)

at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:965)

at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:163)

at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:656)

at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:591)

at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:508)

at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:470)

at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:909)

at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)

at java.lang.Thread.run(Thread.java:748)

Caused by: javax.net.ssl.SSLException: Received fatal alert: certificate_unknown

at sun.security.ssl.Alerts.getSSLException(Alerts.java:208)

at sun.security.ssl.SSLEngineImpl.fatal(SSLEngineImpl.java:1666)

at sun.security.ssl.SSLEngineImpl.fatal(SSLEngineImpl.java:1634)

at sun.security.ssl.SSLEngineImpl.recvAlert(SSLEngineImpl.java:1800)

at sun.security.ssl.SSLEngineImpl.readRecord(SSLEngineImpl.java:1083)

at sun.security.ssl.SSLEngineImpl.readNetRecord(SSLEngineImpl.java:907)

at sun.security.ssl.SSLEngineImpl.unwrap(SSLEngineImpl.java:781)

at javax.net.ssl.SSLEngine.unwrap(SSLEngine.java:624)

at io.netty.handler.ssl.SslHandler$SslEngineType$3.unwrap(SslHandler.java:295)

at io.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1301)

at io.netty.handler.ssl.SslHandler.decodeJdkCompatible(SslHandler.java:1203)

at io.netty.handler.ssl.SslHandler.decode(SslHandler.java:1247)

at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:502)

at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:441)

… 16 common frames omitted

15:46:33.160 [nioEventLoopGroup-3-1] WARN io.netty.channel.DefaultChannelPipeline – An exceptionCaught() event was fired, and it reached at the tail of the pipeline. It usually means the last handler in the pipeline did not handle the exception.

io.netty.handler.codec.DecoderException: javax.net.ssl.SSLException: Received fatal alert: certificate_unknown

at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:472)

at io.netty.handler.codec.ByteToMessageDecoder.channelInputClosed(ByteToMessageDecoder.java:405)

at io.netty.handler.codec.ByteToMessageDecoder.channelInputClosed(ByteToMessageDecoder.java:372)

at io.netty.handler.codec.ByteToMessageDecoder.channelInactive(ByteToMessageDecoder.java:355)

at io.netty.handler.ssl.SslHandler.channelInactive(SslHandler.java:1054)

at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:245)

at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:231)

at io.netty.channel.AbstractChannelHandlerContext.fireChannelInactive(AbstractChannelHandlerContext.java:224)

at io.netty.channel.DefaultChannelPipeline$HeadContext.channelInactive(DefaultChannelPipeline.java:1429)

at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:245)

at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:231)

at io.netty.channel.DefaultChannelPipeline.fireChannelInactive(DefaultChannelPipeline.java:947)

at io.netty.channel.AbstractChannel$AbstractUnsafe$8.run(AbstractChannel.java:826)

at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:163)

at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:404)

at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:474)

at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:909)

at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)

at java.lang.Thread.run(Thread.java:748)

Caused by: javax.net.ssl.SSLException: Received fatal alert: certificate_unknown

at sun.security.ssl.Alerts.getSSLException(Alerts.java:208)

at sun.security.ssl.SSLEngineImpl.fatal(SSLEngineImpl.java:1666)

at sun.security.ssl.SSLEngineImpl.fatal(SSLEngineImpl.java:1634)

at sun.security.ssl.SSLEngineImpl.recvAlert(SSLEngineImpl.java:1800)

at sun.security.ssl.SSLEngineImpl.readRecord(SSLEngineImpl.java:1083)

at sun.security.ssl.SSLEngineImpl.readNetRecord(SSLEngineImpl.java:907)

at sun.security.ssl.SSLEngineImpl.unwrap(SSLEngineImpl.java:781)

at javax.net.ssl.SSLEngine.unwrap(SSLEngine.java:624)

at io.netty.handler.ssl.SslHandler$SslEngineType$3.unwrap(SslHandler.java:295)

at io.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1301)

at io.netty.handler.ssl.SslHandler.decodeJdkCompatible(SslHandler.java:1203)

at io.netty.handler.ssl.SslHandler.decode(SslHandler.java:1247)

at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:502)

at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:441)

… 18 common frames omitted

客户端断开,channle对应的长id为:005056fffec00001-00003328-00000001-371e6fb621ac9d11-9b925be2

客户端断开,channle对应的短id为:9b925be2

 

 

 

 

A good plan

introduce

/** * init class ** netty configure SSL pit record the most secure set of schemes, page access background, to use * 1. Page WSS ://(SSL domain name address applied by Ali cloud or Tencent Cloud)/port/ws * 2 On the server, configure the domain name to be configured into the initialization class using the JKS of the requested SSL * 3. If you are not comfortable with the above method, many times there will be incorrect domain name, or do not let the connection, domain name password abnormal JKS and domain name mismatch and a series of messy problems, * 5. * * @author Jianghy * * @version 1.0 */Copy the code

 

Initializer class plus this

This is the main code

	String jksPath = (System.getProperty("user.dir")+ "/target/classes/ssl/test/ma.yueduixiang.com.jks");
        SSLContext sslContext = SslUtil.createSSLContext("JKS",jksPath,"ma.yueduixiang.com");
        SSLEngine sslEngine = sslContext.createSSLEngine();
        sslEngine.setNeedClientAuth(false);
        sslEngine.setUseClientMode(false);
        pipeline.addLast("sslHandler", new SslHandler(sslEngine));
Copy the code

 

Capture effect

 

Initialize type full code

package com.superman.nettyim; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.DelimiterBasedFrameDecoder; import io.netty.handler.codec.Delimiters; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpServerCodec; import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; import io.netty.handler.ssl.SslHandler; import io.netty.handler.stream.ChunkedWriteHandler; import io.netty.handler.timeout.IdleStateHandler; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; /** * init class ** netty configure SSL pit record the most secure set of schemes, page access background, to use * 1. Page WSS ://(SSL domain name address applied by Ali cloud or Tencent Cloud)/port/ws * 2 On the server, configure the domain name to be configured into the initialization class using the JKS of the requested SSL * 3. If you are not comfortable with the above method, many times there will be incorrect domain name, or do not let the connection, domain name password abnormal JKS and domain name mismatch and a series of messy problems, * 5. If you want, instead of initializing the class every time, you can initialize sslContext. 7. Ok * * @author Jianghy * * @version 1.0 */ public class IMNettyServerInitialzer extends ChannelInitializer<SocketChannel> { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); String jksPath = (System.getProperty("user.dir")+ "/target/classes/ssl/test/ma.yuedxuixiang.com.jks"); SSLContext sslContext = SslUtil.createSSLContext("JKS",jksPath,"ma.yueduixxiangozm"); SSLEngine sslEngine = sslContext.createSSLEngine(); sslEngine.setNeedClientAuth(false); sslEngine.setUseClientMode(false); pipeline.addLast("sslHandler", new SslHandler(sslEngine)); ch.pipeline().addLast(new IdleStateHandler(5, 0, 0, TimeUnit.SECONDS)); AddLast (new HttpServerCodec())); // // support for writing big data streams pipelo.addlast (new ChunkedWriteHandler()); // // to aggregate httpMessage into FullHttpRequest or FullHttpResponse // // almost programming in Netty, Hanler pipeline.addLast(new HttpObjectAggregator(1024*64)); / / = = = = = = = = = = = = = = = = = = = = = = above is used to support the HTTP protocol = = = = = = = = = = = = = = = = = = = = = = / / = = = = = = = = = = = = = = = = = = = = = = httpWebsocket below is support = = = = = = = = = = = = = = = = = = = = = = / * * * the websocket server protocol, is used to specify the client connection can access the routing: /ws * This handler will handle some heavy and complicated things for you * it will handle the handshake for you: * For websockets, all are transmitted in frames, Different data types corresponding to different frames * / pipeline. AddLast (new DelimiterBasedFrameDecoder (8192, Delimiters. LineDelimiter ())); pipeline.addLast(new StringDecoder()); pipeline.addLast(new StringEncoder()); pipeline.addLast(new WebSocketServerProtocolHandler("/ws")); // Custom handler pipeline.addLast(new IMNettyHandler()); }}Copy the code

 

Create SslUtil class

package com.superman.nettyim; import java.io.FileInputStream; import java.io.InputStream; import java.security.KeyStore; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; /** * public class SslUtil {private static volatile SSLContext sslContext = null; /** * Create * @param Type type (JKS) * @param path JKS file path * @param password JKS password * @return * @throws Exception */ public static SSLContext createSSLContext(String type ,String path ,String password) throws Exception { if(null == sslContext){ Synchronized (SslUtil. Class){if(null == sslContext){// support JKS, PKCS12 (we use the certificate is free application, download tomcat decompress PFX file, KeyStore ks = keystore.getInstance (type); InputStream ksInputStream = new FileInputStream(path); ks.load(ksInputStream, password.toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, password.toCharArray()); sslContext = SSLContext.getInstance("TLS"); sslContext.init(kmf.getKeyManagers(), null, null); } } } return sslContext; }}Copy the code

 

The page code

<! DOCTYPE HTML >< HTML >< head> <meta charset=" UTF-8 "/> <title></title> </head> <body> <h3> <input type="text" id="msg0" value="1001"/><br /> Token :<input type="text" id="msg1" value="101"/> <input type="text" id="msg2" value="1" /><br /> 信息 id:< br /> <input type="text" id="msg4" value=" nice "/><br />< input type="button" value=" onclick=" chat.chat ()" />< /p> <div> </div> <div id="receiveMsg" style="background-color: gainsboro;" ></div> <script type="application/javascript"> window.CHAT = { socket: null, init: function () { if (window.WebSocket) { var socketAddress = "wss://ma.yueduixiang.com:9999/ws"; CHAT.socket = new WebSocket(socketAddress); Chat.socket. onopen = function () {console.log(" Connection established successfully... ); }, chat.socket. onclose = function () {console.log(" Connection closed... ); }, chat.socket. onerror = function () {console.log(" error... ); }, chat.socket. onmessage = function (e) {console.log(" received message: "+ e.data); var receiveMsg = document.getElementById("receiveMsg"); var html = receiveMsg.innerHTML; Receivemsg. innerHTML = HTML + "<br/>" + "Received message:" + e.ata; }} else {alert(" Browser does not support websocket protocol..." ); } }, chat: function () { var msg0 = document.getElementById("msg0").value; var msg1 = document.getElementById("msg1").value; var msg2 = document.getElementById("msg2").value; var msg3 = document.getElementById("msg3").value; var msg4 = document.getElementById("msg4").value; CHAT.socket.send(msg0 + "," + msg1 + "," + msg2 + "," + msg3 + "," + msg4); var receiveMsg = document.getElementById("receiveMsg"); var html = receiveMsg.innerHTML; Receivemsg. innerHTML = HTML + "<br/>" + "Send message:" + msg4; }}; CHAT.init(); </script> </body> </html>Copy the code

That’s the main thing

var socketAddress = “wss://ma.yueduixiang.com:9999/ws”;

 

Apply for SSL

Build a detailed framework for my blog

In addition to ssluitL not adding a few lines of code to the initialization class, there is also a page modified ws to WSS :// domain name :port/ws and the rest is the same

Yushen.blog.csdn.net/article/det…

 

 

ok

 

 

Continuously updated

 

In the previous setup, SslContext was created only once, eliminating the need to create each call

Start type

package com.superman.nettyim; import javax.net.ssl.SSLContext; import io.netty.bootstrap.ServerBootstrap; 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.NioServerSocketChannel; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpServerCodec; import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; import io.netty.handler.stream.ChunkedWriteHandler; @author Jianghy ** @version 1.0 */ public class IMNettyServer {private int port = 8088; public IMNettyServer(int port) { this.port = port; } public void run() throws Exception { String jksPath = (System.getProperty("user.dir")+ "/target/classes/ssl/test/ma.yuedasuixisaang.com.jks"); SSLContext sslContext = SslUtil.createSSLContext("JKS",jksPath,"ma.yasueduixasiang.com"); EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1) EventLoopGroup workerGroup = new NioEventLoopGroup(); System.out.println("----------------- netty Server Start--------------------"); try { ServerBootstrap b = new ServerBootstrap(); // (2) b.group(bossGroup, workerGroup) // here we specify that NioServerSocketChannel is used to instantiate the new class Channel to accept incoming connections. .channel(NioServerSocketChannel.class) // (3) .childHandler(new IMNettyServerInitialzer(sslContext)) .option(ChannelOption.SO_BACKLOG, 128) // (5) .childOption(ChannelOption.SO_KEEPALIVE, true); // (6) ChannelFuture f = b.bind(port).sync(); // (7) System.out.println("-------------------netty server port:"+port+" start success -----------"); // Wait for the server socket to close. // In this case, this does not happen, but you can do so // gracefully // shutting down the server. f.channel().closeFuture().sync(); } catch (Exception e) { e.printStackTrace(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } public static void main(String[] args) throws Exception { new IMNettyServer(9999).run(); }}Copy the code

 

Initialization type

package com.superman.nettyim; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.DelimiterBasedFrameDecoder; import io.netty.handler.codec.Delimiters; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpServerCodec; import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; import io.netty.handler.ssl.SslHandler; import io.netty.handler.stream.ChunkedWriteHandler; import io.netty.handler.timeout.IdleStateHandler; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; /** * init class ** netty configure SSL pit record the most secure set of schemes, page access background, to use * 1. Page WSS ://(SSL domain name address applied by Ali cloud or Tencent Cloud)/port/ws * 2 On the server, configure the domain name to be configured into the initialization class using the JKS of the requested SSL * 3. If you are not comfortable with the above method, many times there will be incorrect domain name, or do not let the connection, domain name password abnormal JKS and domain name mismatch and a series of messy problems, * 5. If you want, instead of initializing the class every time, you can initialize sslContext. 7. Ok * * @author Jianghy * * @version 1.0 */ public class IMNettyServerInitialzer extends ChannelInitializer<SocketChannel> { private SSLContext sslContext; public IMNettyServerInitialzer(SSLContext sslContext){ this.sslContext = sslContext; } @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); // String jksPath = (System.getProperty("user.dir")+ "/target/classes/ssl/test/ma.yudedzuixiang.com.jks"); // SSLContext sslContext = SslUtil.createSSLContext("JKS",jksPath,"ma.yuedauisxiang.com"); SSLEngine sslEngine = sslContext.createSSLEngine(); sslEngine.setNeedClientAuth(false); sslEngine.setUseClientMode(false); pipeline.addLast("sslHandler", new SslHandler(sslEngine)); ch.pipeline().addLast(new IdleStateHandler(5, 0, 0, TimeUnit.SECONDS)); AddLast (new HttpServerCodec())); // // support for writing big data streams pipelo.addlast (new ChunkedWriteHandler()); // // to aggregate httpMessage into FullHttpRequest or FullHttpResponse // // almost programming in Netty, Hanler pipeline.addLast(new HttpObjectAggregator(1024*64)); / / = = = = = = = = = = = = = = = = = = = = = = above is used to support the HTTP protocol = = = = = = = = = = = = = = = = = = = = = = / / = = = = = = = = = = = = = = = = = = = = = = httpWebsocket below is support = = = = = = = = = = = = = = = = = = = = = = / * * * the websocket server protocol, is used to specify the client connection can access the routing: /ws * This handler will handle some heavy and complicated things for you * it will handle the handshake for you: * For websockets, all are transmitted in frames, Different data types corresponding to different frames * / pipeline. AddLast (new DelimiterBasedFrameDecoder (8192, Delimiters. LineDelimiter ())); pipeline.addLast(new StringDecoder()); pipeline.addLast(new StringEncoder()); pipeline.addLast(new WebSocketServerProtocolHandler("/ws")); // Custom handler pipeline.addLast(new IMNettyHandler()); }}Copy the code

 

ok  

 

 

 

Continuously updated