之前使用Springboot整合了websocket腐晾,實(shí)現(xiàn)了一個(gè)后端向前端推送信息的基本小案例漓穿,這篇文章主要是增加了一個(gè)新的框架就是Netty,實(shí)現(xiàn)一個(gè)高性能的websocket服務(wù)器惦辛,并結(jié)合前端代碼咬腋,實(shí)現(xiàn)一個(gè)基本的聊天功能。你可以根據(jù)自己的業(yè)務(wù)需求進(jìn)行更改向瓷。
這里假設(shè)你已經(jīng)了解了Netty和websocket的相關(guān)知識肠套,僅僅是想通過Springboot來整合他們。根據(jù)之前大家的需求猖任,代碼已經(jīng)上傳到了github上你稚。在文末給出。
廢話不多說超升,直接看步驟代碼入宦。
一、環(huán)境搭建
名稱版本Idea2018專業(yè)版(已破解)Maven4.0.0SpringBoot2.2.2websocket2.1.3netty4.1.36jdk1.8
其實(shí)對于jar包版本的選擇室琢,不一定按照我的來,只需要接近即可落追,最好的辦法就是直接去maven網(wǎng)站上去查看盈滴,哪一個(gè)版本的使用率最高,說明可靠性等等就是最好的轿钠。Idea我已經(jīng)破解巢钓,需要的私聊我。
二疗垛、整合開發(fā)
建立一個(gè)項(xiàng)目症汹,名字叫做SpringbootNettyWebSocket
1、添加依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.36.Final</version>
</dependency>
2贷腕、在application.properties文件修改端口號
一句話:server.port=8081
3背镇、新建service包,創(chuàng)建NettyServer類
@Component
public class NettyServer {
@Value("${server.port}")
private int port;
@PostConstruct
public void start() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup group = new NioEventLoopGroup();
try {
ServerBootstrap sb = new ServerBootstrap();
sb.option(ChannelOption.SO_BACKLOG, 1024);
sb.group(group, bossGroup)
.channel(NioServerSocketChannel.class)
.localAddress(this.port)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
System.out.println("收到新連接:"+ch.localAddress());
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(port).sync(); // 服務(wù)器異步創(chuàng)建綁
cf.channel().closeFuture().sync(); // 關(guān)閉服務(wù)器通道
} finally {
group.shutdownGracefully().sync(); // 釋放線程池資源
bossGroup.shutdownGracefully().sync();
}
}
}
這個(gè)類的代碼是模板代碼泽裳,最核心的就是ch.pipeline().addLast(new MyWebSocketHandler())瞒斩,其他的如果你熟悉netty的話,可以根據(jù)自己的需求配置即可涮总,如果不熟悉直接拿過來用胸囱。
4、在service包下創(chuàng)建MyWebSocketHandler核心處理類
public class MyWebSocketHandler extends
SimpleChannelInboundHandler<TextWebSocketFrame> {
public static ChannelGroup channelGroup;
static {
channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
}
//客戶端與服務(wù)器建立連接的時(shí)候觸發(fā)瀑梗,
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("與客戶端建立連接烹笔,通道開啟裳扯!");
//添加到channelGroup通道組
channelGroup.add(ctx.channel());
}
//客戶端與服務(wù)器關(guān)閉連接的時(shí)候觸發(fā),
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println("與客戶端斷開連接谤职,通道關(guān)閉饰豺!");
channelGroup.remove(ctx.channel());
}
//服務(wù)器接受客戶端的數(shù)據(jù)信息,
@Override
protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg){
System.out.println("服務(wù)器收到的數(shù)據(jù):" + msg.text());
//sendMessage(ctx);
sendAllMessage();
}
//給固定的人發(fā)消息
private void sendMessage(ChannelHandlerContext ctx) {
String message = "你好柬帕,"+ctx.channel().localAddress()+" 給固定的人發(fā)消息";
ctx.channel().writeAndFlush(new TextWebSocketFrame(message));
}
//發(fā)送群消息,此時(shí)其他客戶端也能收到群消息
private void sendAllMessage(){
String message = "我是服務(wù)器哟忍,這里發(fā)送的是群消息";
channelGroup.writeAndFlush( new TextWebSocketFrame(message));
}
}
在這個(gè)類里面我們首先建立了一個(gè)channelGroup,每當(dāng)有客戶端連接的時(shí)候陷寝,就添加到channelGroup里面锅很,我們可以發(fā)送消息給固定的人,也可以群發(fā)消息凤跑。
注意:有人說這個(gè)功能沒有實(shí)現(xiàn)后臺主動推送的功能爆安。其實(shí)代碼寫到這一步,你可以使用定時(shí)器來實(shí)現(xiàn)定時(shí)推送的功能仔引,另外為了解決跨域的問題扔仓,你也可以使用nginx配置反向代理。我這里只是一個(gè)基本的功能咖耘,沒有使用nginx翘簇。
5、客戶端代碼
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>java的架構(gòu)師技術(shù)棧</title>
<script type="text/javascript">
var socket;
if(!window.WebSocket){
window.WebSocket = window.MozWebSocket;
}
if(window.WebSocket){
socket = new WebSocket("ws://localhost:8081/ws");
socket.onmessage = function(event){
var ta = document.getElementById('responseText');
ta.value += event.data+"\r\n";
};
socket.onopen = function(event){
var ta = document.getElementById('responseText');
ta.value = "已連接";
};
socket.onclose = function(event){
var ta = document.getElementById('responseText');
ta.value = "已關(guān)閉";
};
}else{
alert("您的瀏覽器不支持WebSocket協(xié)議儿倒!");
}
function send(message){
if(!window.WebSocket){return;}
if(socket.readyState == WebSocket.OPEN){
socket.send(message);
}else{
alert("WebSocket 連接沒有建立成功版保!");
}
}
</script>
</head>
<body>
<form onSubmit="return false;">
<hr color="black" />
<h3>客戶端發(fā)送的信息</h3>
<label>名字</label><input type="text" name="uid" value="java的架構(gòu)師技術(shù)棧" /> <br />
<label>內(nèi)容</label><input type="text" name="message" value="hello 我是馮冬冬" /> <br />
<br /> <input type="button" value="點(diǎn)擊發(fā)送" onClick="send(this.form.uid.value+':'+this.form.message.value)" />
<hr color="black" />
<h3>服務(wù)端返回的應(yīng)答消息</h3>
<textarea id="responseText" style="width: 900px;height: 300px;"></textarea>
</form>
</body>
</html>
現(xiàn)在一切就緒,打開我們的服務(wù)器夫否,然后再打開我們的網(wǎng)頁客戶端彻犁。看一下效果吧
同樣的服務(wù)器也是同樣的效果凰慈。這里就不粘貼演示了汞幢。OK,這就是一個(gè)最基本的功能微谓,所有的測試均在我自己的電腦上實(shí)現(xiàn)森篷,如有問題還請指正