我们在开发时,经常需要在前后端之间传递信息。前端的变化要通知给后端,反之,后端的数据更新也要及时通知给前端。那什么样的技术,可以确保前后端之间的高效稳定通信呢?今天 壹哥 就带各位学习WebSockets,实现前后端之间的通信。
WebSocket是HTML5提供的一种新的网络通信协议。它实现了服务端与客户端的全双工通信,建立在传输层TCP协议之上,即浏览器与服务端需要先建立TCP协议,再发送WebSocket连接建立请求。
既然网络通信已经有了http协议,为什么还需要WebSocket协议呢?
这是因为http协议有一个缺陷,通信只能由客户端发起请求,服务器端返回查询结果。
比如说我们想要获取一个实时的新闻信息,在每次更新新闻信息后,我们都需要刷新页面才能获取到最新的信息,只有再次发起客户端请求,服务器端才会返回结果。但是服务器端不能做到推送消息给客户端,当然我们可以使用轮询,查看服务器有没有新的消息,比如 "聊天室" 这样的,但是轮询效率是非常低的,因此WebSocket就这样产生了。
客户端发送请求信息,服务端接收到这个请求并返回响应信息。
当连接建立后,客户端发送http请求时,通过Upgrade:webSocket Connection:Upgrade 告知服务器需要建立的是WebSocket连接,并且还会传递WebSocket版本号、协议的字版本号、原始地址、主机地址, WebSocket相互通信的Header很小,大概只有2Bytes。
WebSocket的最大优点就是服务器可以主动向客户端推送消息,客户端也可以主动向服务器端发送消息。
使用WebSockets可以在服务器与客户端之间建立一个非http的双向连接。这个连接是实时的,也是永久的(除非被关闭)。
当服务器想向客户端发送数据时,可以立即将数据推送到客户端的浏览器中,无需重新建立链接,只要客户端有一个被打开的socket(套接字)并且与服务器建立链接,服务器就可以把数据推送到这个socket上。
WebSocket需要接收一个url参数,然后调用WebSocket对象的构造器来建立与服务器之间的通信链接。
如下代码初始化:
var websocket = new WebSocket('wss://echo.websocket.org');
复制代码
URL字符串必须以 "ws" 或 "wss"(加密通信)开头。
利用上面的代码,我们的通信连接建立之后,就可以进行客户端与服务器端的双向通信了。可以使用WebSocket对象的send方法对服务器发送数据,但是只能发送文本数据(我们可以使用JSON对象把任何js对象转换成文本数据后再进行发送)。
websocket.send("data");
复制代码
通过onmessage事件来接收服务器传过来的数据,如下代码:
websocket.onmessage = function(event) {
var data = event.data;
}
复制代码
通过获取onopen事件来监听socket的打开事件。如下代码:
websocket.onopen = function(event) {
// 开始通信时的处理
}
复制代码
通过获取onclose事件来监听socket的关闭事件。如下代码:
websocket.onclose = function(event) {
// 通信结束时的处理
}
复制代码
通过close方法来关闭socket, 如下代码:
websocket.close();
复制代码
可以通过读取readyState的属性值来获取WebSocket对象的状态,readyState属性存在以下几种属性值。
我们按照之前的经验,创建一个Web项目,并将之改造成Spring Boot项目,具体过程略。
在pom.xml文件中添加核心依赖包。
org.springframework.boot
spring-boot-starter-websocket
org.springframework.boot
spring-boot-starter-thymeleaf
com.alibaba
fastjson
1.2.46
复制代码
我们创建一个配置类,开启对WebSockets的支持。
package com.yyg.boot.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* @Author 一一哥Sun
* @Date Created in 2020/5/13
* @Description Description
*/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
复制代码
接着我们要创建WebSeckets服务端的配置代码,这是通信的核心。
package com.yyg.boot.websockets;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
/**
* @Author 一一哥Sun
* @Date Created in 2020/5/13
* @Description Description
*/
@Component
@ServerEndpoint("/server/{uid}")
@Slf4j
public class WebSocketServer {
/**
* 用来记录当前在线连接数量,应该把它设计成线程安全的。
*/
private static int onlineCount = 0;
/**
* concurrent包是线程安全的Set,用来存放每个客户端对应的WebSocket对象。
*/
private static ConcurrentHashMap webSocketMap = new ConcurrentHashMap<>();
/**
* 与某个客户端的连接会话,需要通过它来给客户端发送数据.
*/
private Session session;
/**
* 接收客户端消息的uid
*/
private String uid = "";
/**
* 连接建立成功调用的方法
*/
@OnOpen
public void onOpen(Session session, @PathParam("uid") String uid) {
this.session = session;
this.uid = uid;
if (webSocketMap.containsKey(uid)) {
webSocketMap.remove(uid);
//加入到set中
webSocketMap.put(uid, this);
} else {
//加入set中
webSocketMap.put(uid, this);
//在线数加1
addOnlineCount();
}
log.info("用户连接:" + uid + ",当前在线人数为:" + getOnlineCount());
try {
sendMsg("连接成功");
} catch (IOException e) {
log.error("用户:" + uid + ",网络异常!!!!!!");
}
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
if (webSocketMap.containsKey(uid)) {
webSocketMap.remove(uid);
//从set中删除
subOnlineCount();
}
log.info("用户退出:" + uid + ",当前在线人数为:" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
* @param message 客户端发送过来的消息
*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("用户id:" + uid + ",接收到的报文:" + message);
//可以群发消息
//消息保存到数据库、redis
if (!StringUtils.isEmpty(message)) {
try {
//解析发送的报文
JSONObject jsonObject = JSON.parseObject(message);
//追加发送人(防止串改)
jsonObject.put("fromUID", this.uid);
String toUID = jsonObject.getString("toUID");
//传送给对应的toUserId用户的WebSocket
if (!StringUtils.isEmpty(toUID) && webSocketMap.containsKey(toUID)) {
webSocketMap.get(toUID).sendMsg(jsonObject.toJSONString());
} else {
//若果不在这个服务器上,可以考虑发送到mysql或者redis
log.error("请求的UserId:" + toUID + "不在该服务器上");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 处理错误
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("用户错误:" + this.uid + ",原因:" + error.getMessage());
error.printStackTrace();
}
/**
* 实现服务器主动推送
*/
private void sendMsg(String msg) throws IOException {
this.session.getBasicRemote().sendText(msg);
}
/**
* 发送自定义消息
*/
public static void sendInfo(String message, @PathParam("uid") String uid) throws IOException {
log.info("发送消息到:" + uid + ",发送的报文:" + message);
if (!StringUtils.isEmpty(uid) && webSocketMap.containsKey(uid)) {
webSocketMap.get(uid).sendMsg(message);
} else {
log.error("用户" + uid + ",不在线!");
}
}
private static synchronized int getOnlineCount() {
return onlineCount;
}
private static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
private static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}
复制代码
编写一个Controller,定义出通信的接口。
package com.yyg.boot.web;
import com.yyg.boot.websockets.WebSocketServer;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import java.io.IOException;
/**
* @Author 一一哥Sun
* @Date Created in 2020/5/13
* @Description Description
*/
@RestController
public class WebSocketController {
@GetMapping("/page")
public ModelAndView page() {
return new ModelAndView("webSocket");
}
@RequestMapping("/push/{toUID}")
public ResponseEntity pushToClient(String message, @PathVariable String toUID) throws IOException {
WebSocketServer.sendInfo(message, toUID);
return ResponseEntity.ok("Send Success!");
}
}
复制代码
编写前端页面,向后端发送通信请求。
WebSocket通讯
【uid】:
【toUID】:
【Msg】:
【第一步操作:】:
【第二步操作:】:
复制代码
在application.yml配置文件中,对我们的项目进行必要的配置。
server:
port: 8080
servlet:
context-path: /socket
spring:
http:
encoding:
force: true
charset: UTF-8
application:
name: websocket-demo
freemarker:
request-context-attribute: request
prefix: /templates/
suffix: .html
content-type: text/html
enabled: true
cache: false
charset: UTF-8
allow-request-override: false
expose-request-attributes: true
expose-session-attributes: true
expose-spring-macro-helpers: true
复制代码
最后创建一个项目入口类,启动项目。
package com.yyg.boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @Author 一一哥Sun
* @Date Created in 2020/5/13
* @Description Description
*/
@SpringBootApplication
public class SocketApplication {
public static void main(String[] args){
SpringApplication.run(SocketApplication.class,args);
}
}
复制代码
此时完整的项目结构如下图所示,大家可以参考创建。
我们需要在浏览器中打开另个页面,网址都是:
http://localhost:8080/socket/page
首先我们在第一个页面中,输入如下参数信息,点击发送消息按钮:
可以看到Console控制台显示的日志信息。然后我们去Intellij idea中看看后台打印的日志信息:
然后我们在第二个页面中,输入如下参数信息,点击发送消息按钮:
然后我们去Intellij idea中看看后台打印的日志信息:
接着我们回到第一个页面,可以看到log中展示了如下信息:
说明接收到了从另一个客户端发来的信息。如果在第一个页面中再次点击发送信息的按钮,同样的在第二个页面中可以收到日志信息:
至此,我们就实现了WebSocket通信。
经过上面的一系列代码,我们就实现了前后端之间的通信。现在你有么有学会WebSocket的使用呢?
原文链接:https://juejin.cn/post/7177139309856686139
来源:稀土掘金
页面更新:2024-04-02
本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828
© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号