代码:
后端:
<dependency>
<groupId>org.t-io</groupId>
<artifactId>tio-websocket-spring-boot-starter</artifactId>
<version>3.3.2.v20190601-RELEASE</version>
</dependency>
public class MyWebSocketMsgHandler implements IWsMsgHandler {
@Override
public HttpResponse handshake(HttpRequest httpRequest, HttpResponse httpResponse, ChannelContext channelContext) throws Exception {
return httpResponse;
}
@Override
public void onAfterHandshaked(HttpRequest httpRequest, HttpResponse httpResponse, ChannelContext channelContext) throws Exception {
System.out.println("握手成功");
}
@Override
public Object onBytes(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) throws Exception {
System.out.println("接收到bytes消息");
return null;
}
@Override
public Object onClose(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) throws Exception {
return null;
}
@Override
public Object onText(WsRequest wsRequest, String s, ChannelContext channelContext) throws Exception {
System.out.println("接收到文本消息:" + s);
return null;
}
@SpringBootApplication
@EnableTioWebSocketServer
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
控制层:
@ServerEndpoint("/websocket")
@RequestMapping("/ws")
@RestController
public class Controller {
@Autowired
private TioWebSocketServerBootstrap bootstrap;
//该方法用于给前端发送数据
@GetMapping("/msg")
public void pushMessage(String msg) {
Tio.sendToAll(bootstrap.getServerGroupContext(), WsResponse.fromText(msg, "utf-8"));
}
}
<div>
<button onclick="aa()">点击发送</button>
</div>
</body>
<script>
//该方法用于给后台发送数据
function aa(){
var ws = new WebSocket("ws://localhost:9876/");
ws.onopen = function (event) {
ws.send("Hello Tio WebSocket");
}
}
//以下代码用于接收客户端发送的数据
var ws = new WebSocket("ws://localhost:9876/ws/msg");
ws.onmessage = function (p1) {
console.log(p1.data);
var elementsByClassName = document.getElementsByClassName("message");
elementsByClassName[0].innerText=p1.data//将其数据显示到页面
}
</script>