Netty最为后端服务处理WebSocket协议连接
后端代码
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.nno</groupId>
<artifactId>nno</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>nno</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.18.Final</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>2.0.5</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.26</version>
</dependency>
</dependencies>
</project>
Server类
package org.nno;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
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 java.util.HashSet;
import java.util.Set;
public class WebSocketServer {
private final int port;
public WebSocketServer(int port) {
this.port = port;
}
Set m = new HashSet();
public void run() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast(new HttpServerCodec());
p.addLast(new HttpObjectAggregator(65536));
p.addLast(new WebSocketServerProtocolHandler("/websocket"));
p.addLast(new WebSocketServerHandler(m));
}
});
ChannelFuture f = b.bind(port).sync();
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
int port = 9911;
if (args.length > 0) {
port = Integer.parseInt(args[0]);
}
new WebSocketServer(port).run();
}
}
Handle类
package org.nno;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import java.util.*;
public class WebSocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
Set m = new HashSet<>();
public WebSocketServerHandler(Set m) {
this.m = m;
}
@Override
public void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
// 处理消息
System.out.println("Received message: " + msg.text());
Iterator<Channel> iterator = m.iterator();
while(iterator.hasNext()){
iterator.next().writeAndFlush(new TextWebSocketFrame("Server received: " + msg.text()));
}
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// 添加连接
System.out.println("Client connected: " + ctx.channel());
m.add(ctx.channel());
Iterator<Channel> iterator = m.iterator();
while(iterator.hasNext()){
iterator.next().writeAndFlush(new TextWebSocketFrame(ctx.channel().localAddress()+"上线啦!"));
}
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
// 断开连接
System.out.println("Client disconnected: " + ctx.channel());
m.remove(ctx.channel());
Iterator<Channel> iterator = m.iterator();
while(iterator.hasNext()){
iterator.next().writeAndFlush(new TextWebSocketFrame(ctx.channel().localAddress()+"下线了!"));
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// 异常处理
cause.printStackTrace();
ctx.close();
}
}
前端页面html
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Talk One</title>
</head>
<body>
<h1>Talk One</h1>
<div>
<input type="text" id="message" placeholder="Message">
</div>
<div id="output"></div>
<script>
var socket = new WebSocket("ws://localhost:9911/websocket");
socket.onopen = function(event) {
console.log("WebSocket opened: " + event);
};
socket.onmessage = function(event) {
console.log("WebSocket message received: " + event.data);
var output = document.getElementById("output");
output.innerHTML += "<p>" + event.data + "</p>";
};
socket.onclose = function(event) {
console.log("WebSocket closed: " + event);
};
function send() {
var message = document.getElementById("message").value;
socket.send(message);
}
document.addEventListener('keydown', function(event) {
if (event.keyCode === 13) {
send()
var txt = document.getElementById('message')
txt.value = ''
}
});
</script>
</body>
</html>
最简单的WebSocket群发聊天室
标签:netty,聊天室,WebSocket,iterator,Netty,io,new,import,channel From: https://blog.csdn.net/airyearth/article/details/142337802