1在pom.xml中加入依赖
<dependency>
<groupId>org.yeauty</groupId>
<artifactId>netty-websocket-spring-boot-starter</artifactId>
<version>0.8.0</version>
</dependency>
2.在springboot的配置文件中加入netty服务器地址和端口号
在application.yml中加入下面代码
netty_socket:
host: 192.168.1.1
path: /
port: 9999
3.配置netty的实体类
package cn.stylefeng.guns.core.Netty;
import io.netty.channel.ChannelId;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.timeout.IdleStateEvent;
import org.springframework.stereotype.Component;
import org.yeauty.annotation.*;
import org.yeauty.pojo.ParameterMap;
import org.yeauty.pojo.Session;
import java.io.IOException;
import java.util.HashMap;
@ServerEndpoint(prefix = "netty_socket")
@Component
public class MyWebSocket {
public static HashMap<ChannelId, Session> nettySession=new HashMap<ChannelId, Session> ();
@OnOpen
public void onOpen(Session session, HttpHeaders headers, ParameterMap parameterMap) throws IOException {
String id = URLDecoder.decode(parameterMap.getParameterValues("userId").get(0), "utf-8");
System.out.println(session.id()+"加入");
nettySession.put(session.id(),session);
}
@OnClose
public void onClose(Session session) throws IOException {
System.out.println(session.id()+"退出");
nettySession.remove(session.id());
}
@OnError
public void onError(Session session, Throwable throwable) {
throwable.printStackTrace();
}
@OnMessage
public void onMessage(Session session, String message) {
session.sendText(message);
}
@OnBinary
public void onBinary(Session session, byte[] bytes) {
for (byte b : bytes) {
System.out.println(b);
}
session.sendBinary(bytes);
}
@OnEvent
public void onEvent(Session session, Object evt) {
if (evt instanceof IdleStateEvent) {
IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
switch (idleStateEvent.state()) {
case READER_IDLE:
System.out.println("read idle");
break;
case WRITER_IDLE:
System.out.println("write idle");
break;
case ALL_IDLE:
System.out.println("all idle");
break;
default:
break;
}
}
}
}
4.后台代码具体实现
在controller或者service中加入
MyWebSocket so = new MyWebSocket();
for (Map.Entry<ChannelId, Session> m : so.nettySession.entrySet()) {
so.onMessage(m.getValue(), "aaaaaaaaaaa");
}
4.前台websocket具体实现
var wsServer = 'ws://192.168.1.1:9999?userId=' + this.$store.state.user.userInfo.user_id;
var websocket = new WebSocket(wsServer);
//监听连接打开
var socketflag;
websocket.onopen = function (evt) {
socketflag = 0;
};
//监听服务器数据推送
websocket.onmessage = function (evt) {
alert(evt.data);
};
function reconnect() {
setTimeout(function () {
websocket = new WebSocket('ws://192.168.1.58:8082/');
websocket.onclose = function () {
reconnect()
};
websocket.onerror = function () {
reconnect()
};
websocket.onmessage = function (evt) {
if(evt.data == 1) {
}
};
}, 2000);
}
//监听连接关闭
websocket.onclose = function (evt) {
reconnect()
};