二手网站建设论文,临沂手工活外发加工网,在国外怎么做网站,花生壳网站无法登陆WebSocket 是基于 TCP 的一种新的网络协议。它实现了浏览器与服务器全双工通信——浏览器和服务器只需要完成一次握手#xff0c;两者之间就可以创建持久性的连接#xff0c; 并进行双向数据传输
HTTP协议和WebSocket协议对比#xff1a;
HTTP是短连接WebSocket是长连接HT…WebSocket 是基于 TCP 的一种新的网络协议。它实现了浏览器与服务器全双工通信——浏览器和服务器只需要完成一次握手两者之间就可以创建持久性的连接 并进行双向数据传输
HTTP协议和WebSocket协议对比
HTTP是短连接WebSocket是长连接HTTP通信是单向的基于请求响应模式WebSocket支持双向通信HTTP和WebSocket底层都是TCP连接
WebSocket应用场景
视频弹幕网页聊天体育实况更新股票基金报价实时更新
websocket详解
1、使用websocket.html页面作为WebSocket客户端
2、maven坐标
dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-websocket/artifactId
/dependency3、定义WebSocket服务端组件
// 用于和客户端通信
Component
ServerEndpoint(/ws/{sid})
public class WebSocketServer {private static MapString, Session sessionMap new HashMap();/*** 连接建立成功调用的方法*/OnOpenpublic void onOpen(Session session, PathParam(sid) String sid){System.out.println(客户端sid建立连接);sessionMap.put(sid,session);}/** 收到客户端消息后调用的方法* message 客户端发送过来的消息*/OnMessagepublic void onMessage(String message,PathParam() String sid){System.out.println(收到客户端sid的消息message);}/*** 关闭连接* param sid*/OnClosepublic void onClose(PathParam() String sid){System.out.println(连接断开sid);sessionMap.remove(sid);}public void sendToAllClient(String message){CollectionSession sessions sessionMap.values();for (Session session:sessions){try {//服务器向客户端发送消息session.getBasicRemote().sendText(message);}catch (Exception e){e.printStackTrace();}}}4、配置类
/*** WebSocket配置类用于注册WebSocket的Bean*/
Configuration
public class WebSocketConfiguration {Beanpublic ServerEndpointExporter serverEndpointExporter(){return new ServerEndpointExporter();}
}5、定时任务定时向客户端推送数据
Component
public class WebSocketTask {Autowiredprivate WebSocketServer webSocketServer;/*** 通过WebSocket每隔5秒向客户端发送消息*/Scheduled(cron 0/5 * * * * ?)public void sendMessageToClient() {webSocketServer.sendToAllClient(这是来自服务端的消息 DateTimeFormatter.ofPattern(HH:mm:ss).format(LocalDateTime.now()));}
}