websocket
直接使用SpringBoot+Netty来支持WebSocket,并且需要支持wss
,其需要注意事项有以下:
-
wss
支持 - websocket请求路径中带参数
针对第一个问题:wss
支持比较简单;
- 生成证书
- ChannelPipeline中添加
ssl
Handler,并且放在First即可。
生成证书
keytool -genkey -alias demo -keypass 123456 -keyalg RSA -keysize 1024 -validity 365 -keystore demo.liukun.com.keystore -storepass 123456 -dname "C=CN,ST=SH,L=SH,O=hfjy,CN=demo.liukun.com" -deststoretype pkcs12
导出证书:
keytool -export -alias demo -file demo.cer -keystore demo.liukun.com.keystore -storepass 123456
ssl/tls支持
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
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.ssl.SslHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyStore;
public class NettyServerHandlerInitializer extends ChannelInitializer<Channel> {
// 证书中使用的密码,因为demo,不做配置,直接写死
private String password = "123456";
@Override
protected void initChannel(Channel ch) throws Exception {
ch.pipeline().addLast(new HttpServerCodec());
ch.pipeline().addLast(new HttpObjectAggregator(65535));
ch.pipeline().addLast(new ChunkedWriteHandler());
// 对websocket url中的参数做解析处理的Handler
ch.pipeline().addLast(new CustomUrlHandler());
// 对websocket做支持,其路径为/ws
ch.pipeline().addLast(new WebSocketServerProtocolHandler("/ws"));
// 自定义业务逻辑处理的Handler
ch.pipeline().addLast(new MyWebSocketHandler());
// 以下为要支持wss所需处理
KeyStore ks = KeyStore.getInstance("JKS");
InputStream ksInputStream = new FileInputStream("/Users/liukun/ca/demo.liukun.com.keystore");
ks.load(ksInputStream, password.toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, password.toCharArray());
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(kmf.getKeyManagers(), null, null);
SSLEngine sslEngine = sslContext.createSSLEngine();
sslEngine.setUseClientMode(false);
sslEngine.setNeedClientAuth(false);
// 需把SslHandler添加在第一位
ch.pipeline().addFirst("ssl", new SslHandler(sslEngine));
}
}
针对第二个问题:websocket的uri中带参数问题。因为在实际项目中,很多情况下都需要使用到参数,如对请求的URL进行认证等,如果需要传递参数通常有两种做法:
- 在Header中传递:这种需要对XMLHttpRequest进行自定义,比较复杂,不建议
- 直接在uri中带参数,如
/ws?token=123
,这种比较简单,建议使用这种,以下处理也是基于这种方式
通过在uri中带参数时,如果使用WebSocketServerProtocolHandler
时会发现连接不成功,因为其不识别这种处理方式。其解决方式:
在其处理之前对uri中的参数解析,并对uri进行重写:即把路径中?
及其后面参数去除。如业务中涉及认证及关联等都在此处理
见上面代码中添加的ch.pipeline().addLast(new CustomUrlHandler())
。其中CustomUrlHandler
内容如下:
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;
import org.eclipse.jetty.util.MultiMap;
import org.eclipse.jetty.util.UrlEncoded;
@ChannelHandler.Sharable
public class CustomUrlHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// 只针对FullHttpRequest类型的做处理,其它类型的自动放过
if (msg instanceof FullHttpRequest) {
FullHttpRequest request = (FullHttpRequest) msg;
String uri = request.uri();
int idx = uri.indexOf("?");
if (idx > 0) {
String query = uri.substring(idx + 1);
// uri中参数的解析使用的是jetty-util包,其性能比自定义及正则性能高。
MultiMap<String> values = new MultiMap<String>();
UrlEncoded.decodeTo(query, values, "UTF-8");
request.setUri(uri.substring(0, idx));
}
}
ctx.fireChannelRead(msg);
}
}
其中MyWebSocketHandler
作用为:收到客户端发送的消息,然后重新传给客户端,注意写数据时格式为TextWebSocketFrame
:
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ChannelHandler.Sharable
public class MyWebSocketHandler extends ChannelInboundHandlerAdapter {
private static final Logger logger = LoggerFactory.getLogger(MyWebSocketHandler.class);
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
logger.info("与客户端建立连接,通道开启");
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
logger.info("与客户端断开连接,通道关闭");
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
TextWebSocketFrame message = (TextWebSocketFrame)msg;
logger.info("服务端收到数据: " + message.text());
// 此处需注意返回的数据的格式为TextWebSocketFrame。否则客户端收不到消息
ctx.channel().writeAndFlush(new TextWebSocketFrame(message.text()));
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
logger.error(cause.getMessage());
cause.printStackTrace();
}
}
其它代码参考如下:
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.net.InetSocketAddress;
@Component
@Slf4j
public class NettyServer {
private EventLoopGroup boss = new NioEventLoopGroup();
private EventLoopGroup work = new NioEventLoopGroup();
private Integer port = 8000;
@PostConstruct
public void start() throws InterruptedException {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(boss, work)
.channel(NioServerSocketChannel.class)
.localAddress(new InetSocketAddress("demo.liukun.com", port))
.option(ChannelOption.SO_BACKLOG, 1024)
.childOption(ChannelOption.SO_KEEPALIVE, true)
.childOption(ChannelOption.TCP_NODELAY, true)
.childHandler(new NettyServerHandlerInitializer());
ChannelFuture future = bootstrap.bind().sync();
if (future.isSuccess()) {
log.info("启动Netty Server");
}
}
@PreDestroy
public void destory() throws InterruptedException {
boss.shutdownGracefully().sync();
work.shutdownGracefully().sync();
log.info("关闭Netty");
}
}
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class NettyApplication {
public static void main(String[] args) {
SpringApplication.run(NettyApplication.class, args);
}
}
前端html页面如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<textarea id="msgBoxs"></textarea><br>
待发送消息:<input type="text" id="msg"><input type="button" id="sendBtn" onclick="send()" value="发送">
<script type="application/javascript">
var msgBoxs = document.getElementById("msgBoxs")
var msgBox = document.getElementById("msg")
document.cookie="token2=John Doe";
var ws = new WebSocket("wss://demo.liukun.com:8000/ws?token=abc123&type=1")
ws.onopen = function (evt) {
console.log("Connection open ...");
ws.send("Hello WebSocket!");
}
ws.onmessage = function (evt) {
console.log("Received Message: ", evt.data)
var msgs = msgBoxs.value
msgBoxs.innerText = msgs + "\n" + evt.data
msgBoxs.scrollTop = msgBoxs.scrollHeight;
}
ws.onclose = function (evt) {
console.log("Connect closed.");
}
function send() {
var msg = msgBox.value
ws.send(msg)
msgBox.value = ""
}
</script>
</body>
</html>
测试
直接使用html页面访问wss服务器时,不同的浏览器会有不同的表现形式:
- firefox不生效
- chome必须先访问其https网址,信任后才生效,否则不生效。
- safari只要信任了证书,直接可以使用:直接在html页面里面即可以访问wss,有mac的同学建议直接使用此方式,最为简单。