SpringBoot2+Netty+WebSocket(netty实现websocket,。。。关于Netty
Netty 是⼀个利⽤ Java 的⾼级⽹络的能⼒,隐藏其背后的复杂性⽽提供⼀个易于使⽤的 API 的客户端/服务器框架。
更新
2019-7-11 新增URL参数⽀持,并解决了带参URL导致的连接⾃动断开问题,感谢⼤家的⽀持。
MAVEN依赖
<dependencies>
<!-- mvnrepository/artifact/ioty/netty-all -->
<dependency>
<groupId>ioty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.36.Final</version>
</dependency>
</dependencies>
SpringBootApplication
启动器中需要new⼀个NettyServer,并显式调⽤启动netty。
@SpringBootApplication
public class SpringCloudStudyDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringCloudStudyDemoApplication.class,args);
try {
new NettyServer(12345).start();
System.out.println("blog.csdn/moshowgame");
System.out.println("127.0.0.1:6688/netty-websocket/index");
}catch(Exception e) {
System.out.println("NettyServerError:"+e.getMessage());
}
}
}
NettyServer
启动的NettyServer,这⾥进⾏配置
/**
* NettyServer Netty服务器配置
* @author zhengkai.blog.csdn
* @date 2019-06-12
*/
public class NettyServer {
private final int port;
public NettyServer(int port) {
this.port = port;
}
public void start() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup group = new NioEventLoopGroup();
try {
ServerBootstrap sb = new ServerBootstrap();
sb.option(ChannelOption.SO_BACKLOG, 1024);
.channel(NioServerSocketChannel.class) // 指定使⽤的channel
.localAddress(this.port)// 绑定监听端⼝
.childHandler(new ChannelInitializer<SocketChannel>() { // 绑定客户端连接时候触发操作
@Override
protected void initChannel(SocketChannel ch) throws Exception {
System.out.println("收到新连接");
//websocket协议本⾝是基于http协议的,所以这边也要使⽤http解编码器
ch.pipeline().addLast(new HttpServerCodec());
/
/以块的⽅式来写的处理器
ch.pipeline().addLast(new ChunkedWriteHandler());
ch.pipeline().addLast(new HttpObjectAggregator(8192));
ch.pipeline().addLast(new WebSocketServerProtocolHandler("/ws", null, true, 65536 * 10));
ch.pipeline().addLast(new MyWebSocketHandler());
}
});
ChannelFuture cf = sb.bind().sync(); // 服务器异步创建绑定
System.out.println(NettyServer.class + " 启动正在监听: " + cf.channel().localAddress());
cf.channel().closeFuture().sync(); // 关闭服务器通道
} finally {
group.shutdownGracefully().sync(); // 释放线程池资源
bossGroup.shutdownGracefully().sync();
}
}
}
MyChannelHandlerPool
通道组池,管理所有websocket连接
/**
* MyChannelHandlerPool
* 通道组池,管理所有websocket连接
* @author zhengkai.blog.csdn
* @date 2019-06-12
*/
public class MyChannelHandlerPool {
public MyChannelHandlerPool(){}
public static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
}
MyWebSocketHandler
处理ws⼀下⼏种情况:
channelActive与客户端建⽴连接
channelInactive与客户端断开连接
channelRead0客户端发送消息处理
/**
* NettyServer Netty服务器配置
* @author zhengkai.blog.csdn
* @date 2019-06-12
*/
public class NettyServer {
private final int port;
public NettyServer(int port) {
this.port = port;
}
public void start() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup group = new NioEventLoopGroup();
try {
ServerBootstrap sb = new ServerBootstrap();
sb.option(ChannelOption.SO_BACKLOG, 1024);
.channel(NioServerSocketChannel.class) // 指定使⽤的channel
.localAddress(this.port)// 绑定监听端⼝
.childHandler(new ChannelInitializer<SocketChannel>() { // 绑定客户端连接时候触发操作
@Override
protected void initChannel(SocketChannel ch) throws Exception {
System.out.println("收到新连接");
//websocket协议本⾝是基于http协议的,所以这边也要使⽤http解编码器
ch.pipeline().addLast(new HttpServerCodec());
//以块的⽅式来写的处理器
ch.pipeline().addLast(new ChunkedWriteHandler());
ch.pipeline().addLast(new HttpObjectAggregator(8192));
ch.pipeline().addLast(new WebSocketServerProtocolHandler("/ws", "WebSocket", true, 65536 * 10)); ch.pipeline().addLast(new MyWebSocketHandler());
}
});
ChannelFuture cf = sb.bind().sync(); // 服务器异步创建绑定
System.out.println(NettyServer.class + " 启动正在监听: " + cf.channel().localAddress());
cf.channel().closeFuture().sync(); // 关闭服务器通道
} finally {
group.shutdownGracefully().sync(); // 释放线程池资源
bossGroup.shutdownGracefully().sync();
}
}
}
socket.html
主要是连接ws,发送消息,以及消息反馈
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "/TR/xhtml1/DTD/xhtml1transitional.dtd"> <html xmlns="/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Netty-Websocket</title>
<script type="text/javascript">
// by zhengkai.blog.csdn
var socket;
if(!window.WebSocket){
window.WebSocket = window.MozWebSocket;
}
if(window.WebSocket){
socket = new WebSocket("ws://127.0.0.1:12345/ws");
var ta = ElementById('responseText');
ta.value += event.data+"\r\n";
};
var ta = ElementById('responseText');
ta.value = "Netty-WebSocket服务器。。。。。。连接 \r\n";
};
websocket和socketvar ta = ElementById('responseText');
ta.value = "Netty-WebSocket服务器。。。。。。关闭 \r\n";
};
}else{
alert("您的浏览器不⽀持WebSocket协议!");
}
function send(message){
if(!window.WebSocket){return;}
adyState == WebSocket.OPEN){
socket.send(message);
}else{
alert("WebSocket 连接没有建⽴成功!");
}
}
</script>
</head>
<body>
<form onSubmit="return false;">
<label>ID</label><input type="text" name="uid" value="${uid!!}" /> <br />
<label>TEXT</label><input type="text" name="message" value="这⾥输⼊消息" /> <br />
<br /> <input type="button" value="发送ws消息"
onClick="send(this.form.uid.value+':'+ssage.value)" />
<hr color="black" />
<h3>服务端返回的应答消息</h3>
<textarea id="responseText" ></textarea>
</form>
</body>
</html>
Controller
写好了html当然还需要⼀个controller来引导页⾯。
@RestController
public class IndexController {
@GetMapping("/index")
public ModelAndView index(){
ModelAndView mav=new ModelAndView("socket");
mav.addObject("uid", RandomUtil.randomNumbers(6));
return mav;
}
}
效果演⽰
思路优化
由于netty不能像默认的websocket⼀样设置⼀些PathVariable例如{uid}等参数(暂未发现可以,如果有发现欢迎补充),所以很多时候发送到后台的报⽂可以设置⼀些特殊的格式,例如上⽂的004401:⼤家好,可以分解为userid:text,当然userid也可以是加密的⼀些报⽂,甚⾄可以学习其他报⽂⼀样设置加密区,这取决于⼤家的业务需要. (已更新解决⽅案)
后⾔
项⽬已经整合进开源项⽬的⼦模块,作为对websocket体系的补充,对的完善。
改造netty⽀持url参数
1. ⾸先,调整⼀下加载handler的顺序,优先MyWebSocketHandler在WebSocketServerProtocolHandler之上。
ch.pipeline().addLast(new MyWebSocketHandler());
ch.pipeline().addLast(new WebSocketServerProtocolHandler("/ws", null, true, 65536 * 10));
1
2
2. 其次,改造MyWebSocketHandler的channelRead⽅法,⾸次连接会是⼀个FullHttpRequest类型,可以通过FullHttpRequest.uri()获取完整ws的
URL地址,之后接受信息的话,会是⼀个TextWebSocketFrame类型。
public class MyWebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("与客户端建⽴连接,通道开启!");
//添加到channelGroup通道组
MyChannelHandlerPool.channelGroup.add(ctx.channel());
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println("与客户端断开连接,通道关闭!");
//添加到channelGroup 通道组
ve(ctx.channel());
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//⾸次连接是FullHttpRequest,处理参数 by zhengkai.blog.csdn
if (null != msg && msg instanceof FullHttpRequest) {
FullHttpRequest request = (FullHttpRequest) msg;
String uri = request.uri();
Map paramMap=getUrlParams(uri);
System.out.println("接收到的参数是:"+JSONString(paramMap));
//如果url包含参数,需要处理
ains("?")){
String newUri=uri.substring(0,uri.indexOf("?"));
System.out.println(newUri);
request.setUri(newUri);
}
}else if(msg instanceof TextWebSocketFrame){
//正常的TEXT消息类型
TextWebSocketFrame frame=(TextWebSocketFrame)msg;
System.out.println("客户端收到服务器数据:" +());
());
}
super.channelRead(ctx, msg);
}
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
}
private void sendAllMessage(String message){
//收到信息后,发给所有channel
MyChannelHandlerPool.channelGroup.writeAndFlush( new TextWebSocketFrame(message));
}
private static Map getUrlParams(String url){
Map<String,String> map = new HashMap<>();
url = place("?",";");
if (!ains(";")){
return map;
}
if (url.split(";").length > 0){
String[] arr = url.split(";")[1].split("&");
for (String s : arr){
String key = s.split("=")[0];
String value = s.split("=")[1];
map.put(key,value);
}
return map;
}else{
return map;
}
}
}
3. html中的ws地址也进⾏改造
socket = new WebSocket("ws://127.0.0.1:12345/ws?uid=666&gid=777");
1
4. 改造后控制台输出情况
收到新连接
与客户端建⽴连接,通道开启!
接收到的参数是:{"uid":"666","gid":"777"}
/ws
客户端收到服务器数据:142531:这⾥输⼊消息
客户端收到服务器数据:142531:这⾥输⼊消息
客户端收到服务器数据:142531:这⾥输⼊消息
1
2
3
4
5
6
7
8
failed: WebSocket opening handshake timed out
听说是ssl wss的情况下才会出现,来⾃ @around-gao 的解决⽅法:
把MyWebSocketHandler和WebSocketServerProtocolHandler调下顺序就好了。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论