<!--建立一个maven工程,然后导入依赖 -->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.31.Final</version>
</dependency>
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
public class webSocketNetty {
public static void main(String[] args) {
NioEventLoopGroup mainGrp = new NioEventLoopGroup();
NioEventLoopGroup subGrp = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap
.group(mainGrp,subGrp)
.channel(NioServerSocketChannel.class)
.childHandler(new WebSocketChannelInitializer());
ChannelFuture future = serverBootstrap.bind(9090).sync();
future.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
mainGrp.shutdownGracefully();
subGrp.shutdownGracefully();
}
}
}
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
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;
public class WebSocketChannelInitializer extends ChannelInitializer<SocketChannel> {
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new HttpServerCodec());
pipeline.addLast(new ChunkedWriteHandler());
pipeline.addLast(new HttpObjectAggregator(1024 * 64));
pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
pipeline.addLast(new ChatHandler());
}
}
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
private static ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
protected void channelRead0(ChannelHandlerContext chc, TextWebSocketFrame msg) throws Exception {
String text = msg.text();
System.out.println("接受到的消息为:" + text);
clients.forEach(x -> {
x.writeAndFlush(new TextWebSocketFrame(formatter.format(LocalDateTime.now()) + ":" + text));
});
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
clients.add(ctx.channel());
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="text" id="msg">
<input type="button" value="发送消息" onclick="sendMsg()">
接受到的消息:
<p id="server_msg" style="background-color: #AAAAAA"></p>
<script>
var webSocket = null;
<!-- 判断当前浏览器是否支持web socket -->
if(window.WebSocket){
webSocket = new WebSocket("ws://127.0.0.1:9090/ws");
webSocket.onopen = function (ev) {
console.log("简历连接");
}
webSocket.onclose = function (ev) {
console.log("关闭连接");
}
webSocket.onmessage = function (ev) {
console.log("接受到服务器的消息" + ev.data);
var serverMsg = document.getElementById("server_msg");
serverMsg.innerHTML += ev.data + "<br/>"
}
}else{
alert("当前浏览器不支持web socket")
}
function sendMsg() {
var message = document.getElementById("msg");
webSocket.send(message.value);
}
</script>
</body>
</html>