1、创建一个简单的maven工程
创建一个简单的maven工程,导入依赖,工程结构如下:
1.1 pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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>com.zdw.netty</groupId>
<artifactId>Netty_Chat</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<target>1.8</target>
<source>1.8</source>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.15.Final</version>
</dependency>
</dependencies>
</project>
1.2 Netty服务WebSocketServer
package com.zdw.netty;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
/**
* Create By zdw on 2019/7/18
*/
public class WebSocketServer {
public static void main(String[] args) {
//初始化主线程池
NioEventLoopGroup mainGroup = new NioEventLoopGroup();
//初始化从线程池
NioEventLoopGroup subGroup = new NioEventLoopGroup();
try {
//创建服务器启动器
ServerBootstrap serverBootstrap = new ServerBootstrap();
//指定使用主线程池和从线程池
serverBootstrap.group(mainGroup,subGroup)
//指定使用nio通道类型
.channel(NioServerSocketChannel.class)
//指定通道初始化器加载通道处理器
.childHandler(new WsServerInitializer());
//绑定端口号启动服务器,并等待服务器启动,ChannelFuture是Netty的回调消息
ChannelFuture future = serverBootstrap.bind(9090).sync();
//等待服务器socket关闭
future.channel().closeFuture().sync();
}catch (Exception e){
e.printStackTrace();
}finally {
//优雅的关闭线程池
mainGroup.shutdownGracefully();
subGroup.shutdownGracefully();
}
}
}
1.3 通道初始化器
package com.zdw.netty;
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;
/**
* Create By zdw on 2019/7/18
* 编写通道初始化器
*/
public class WsServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
// -----------------------------------用于支持Http协议
// websocket基于http协议,需要有http的编解码器
pipeline.addLast(new HttpServerCodec());
// 对写大数据流的支持
pipeline.addLast(new ChunkedWriteHandler());
// 添加对HTTP请求和响应的聚合器:只要使用Netty进行Http编程都需要使用
// 对HttpMessage进行聚合,聚合成FullHttpRequest或者FullHttpResponse
// 在netty编程中都会使用到Handler
pipeline.addLast(new HttpObjectAggregator(1024*64));
// ---------支持Web Socket -----------------
// websocket服务器处理的协议,用于指定给客户端连接访问的路由: /ws
// 本handler会帮你处理一些握手动作: handshaking(close, ping, pong) ping + pong = 心跳
// 对于websocket来讲,都是以frames进行传输的,不同的数据类型对应的frames也不同
pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
//添加自定义的Handler
pipeline.addLast(new ChatHandler());
}
}
1.4 自定义处理消息的Handler
package com.zdw.netty;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
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.EventExecutorGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import java.time.LocalDateTime;
/**
* Create By zdw on 2019/7/18
* 编写自定义处理消息的Handler
* TextWebSocketFrame: 在netty中,是用于为websocket专门处理文本的对象,frame是消息的载体
*/
public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
// 用于记录和管理所有客户端的Channel
private static ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
// 获取从客户端传输过来的消息
String msg = textWebSocketFrame.text();
System.out.println("接收到客户端的消息:"+msg);
//将接收到的消息发送到所有的客户端
for(Channel channel : clients){
// 注意所有的websocket数据都应该以TextWebSocketFrame进行封装
channel.writeAndFlush(new TextWebSocketFrame("服务器接收的消息:"+ LocalDateTime.now()+",消息是:"+msg));
}
}
/**
* 当客户端连接服务端之后(打开连接)
* 获取客户端的channel,并且放入到ChannelGroup中去进行管理
* @param ctx
* @throws Exception
*/
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
clients.add(ctx.channel());
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
// 当触发handlerRemoved,ChannelGroup会自动移除对应客户端的channel
//clients.remove(ctx.channel());
// asLongText()——唯一的ID
// asShortText()——短ID(有可能会重复)
System.out.println("客户端断开, channel对应的长id为:" + ctx.channel().id().asLongText());
System.out.println("客户端断开, channel对应的短id为:" + ctx.channel().id().asShortText());
}
}
1.5 前台页面html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div>发送消息</div>
<input type="text" id="msgContent" />
<input type="button" value="点击发送" onclick="CHAT.chat()"/>
<div>接收消息:</div>
<div id="recMsg" style="background-color: gainsboro;"></div>
<script type="application/javascript">
window.CHAT = {
socket: null,
init: function() {
// 判断浏览器是否支持websocket
if(window.WebSocket) {
// 支持WebScoekt
// 连接创建socket,注意要添加ws后缀
CHAT.socket = new WebSocket("ws://127.0.0.1:9090/ws");
CHAT.socket.onopen = function() {
console.log("连接建立成功");
};
CHAT.socket.onclose = function() {
console.log("连接关闭")
};
CHAT.socket.onerror = function() {
console.log("发生错误");
};
CHAT.socket.onmessage = function(e) {
console.log("接收到消息:" + e.data);
var recMsg = document.getElementById("recMsg");
var html = recMsg.innerHTML;
recMsg.innerHTML = html + "<br/>" + e.data;
};
}else {
alert("浏览器不支持websocket协议");
}
},
chat: function() {
var msg = document.getElementById("msgContent");
CHAT.socket.send(msg.value);
}
}
CHAT.init();
</script>
</body>
</html>
1.6 启动测试
首先是启动WebSocketServer服务类中的main方法。
然后在chat.html页面的文件中,右键单击,在浏览器打开这个文件:
打开之后效果如下:
我们可以多开几个窗口,在某一个窗口中点击发送,会发现每个窗口中都能收到消息:
我们关闭这几个打开的窗口,后台的控制台信息如下:
以上内容参考传智播客资料