WebSocket

介绍

HTTP协议和WebSocket协议对比:

  • HTTP是短连接

  • WebSocket是长连接

  • HTTP通信是单向的,基于请求响应模式

  • WebSocket支持双向通信

  • HTTP和WebSocket底层都是TCP连接

实现步骤 

C端代码(浏览器)

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="UTF-8">
    <title>WebSocket Demo</title>
</head>
<body>
    <input id="text" type="text" />
    <button onclick="send()">发送消息</button>
    <button onclick="closeWebSocket()">关闭连接</button>
    <div id="message">
    </div>
</body>
<script type="text/javascript">
    var websocket = null;
    var clientId = Math.random().toString(36).substr(2);

    //判断当前浏览器是否支持WebSocket
    if('WebSocket' in window){
        //连接WebSocket节点
        websocket = new WebSocket("ws://localhost:8080/ws/"+clientId);
    }
    else{
        alert('Not support websocket')
    }

    //连接发生错误的回调方法
    websocket.onerror = function(){
        setMessageInnerHTML("error");
    };

    //连接成功建立的回调方法
    websocket.onopen = function(){
        setMessageInnerHTML("连接成功");
    }

    //接收到消息的回调方法
    websocket.onmessage = function(event){
        setMessageInnerHTML(event.data);
    }

    //连接关闭的回调方法
    websocket.onclose = function(){
        setMessageInnerHTML("close");
    }

    //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
    window.onbeforeunload = function(){
        websocket.close();
    }

    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML){
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }

    //发送消息
    function send(){
        var message = document.getElementById('text').value;
        websocket.send(message);
    }
	
	//关闭连接
    function closeWebSocket() {
        websocket.close();
    }
</script>
</html>

 导入坐标pom.xml

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

websocketserver 

package com.sky.websocket;

import org.springframework.stereotype.Component;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * WebSocket服务
 */
@Component
@ServerEndpoint("/ws/{sid}")
public class WebSocketServer {

    //存放会话对象
    private static Map<String, Session> sessionMap = new HashMap();

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) {
        System.out.println("客户端:" + sid + "建立连接");
        sessionMap.put(sid, session);
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, @PathParam("sid") String sid) {
        System.out.println("收到来自客户端:" + sid + "的信息:" + message);
    }

    /**
     * 连接关闭调用的方法
     *
     * @param sid
     */
    @OnClose
    public void onClose(@PathParam("sid") String sid) {
        System.out.println("连接断开:" + sid);
        sessionMap.remove(sid);
    }

    /**
     * 群发
     *
     * @param message
     */
    public void sendToAllClient(String message) {
        Collection<Session> sessions = sessionMap.values();
        for (Session session : sessions) {
            try {
                //服务器向客户端发送消息
                session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

导入配置类

package com.sky.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * WebSocket配置类,用于注册WebSocket的Bean
 */
@Configuration
public class WebSocketConfiguration {

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

}

如果想要使用的话使用在目标类注入WebsocketServer 调用其中的方法就可以 

相关推荐

  1. WebSocket

    2023-12-07 20:32:07       42 阅读
  2. websocket

    2023-12-07 20:32:07       28 阅读
  3. WebSocket

    2023-12-07 20:32:07       40 阅读
  4. <span style='color:red;'>WebSocket</span>

    WebSocket

    2023-12-07 20:32:07      27 阅读
  5. <span style='color:red;'>WebSocket</span>

    WebSocket

    2023-12-07 20:32:07      42 阅读
  6. WebSocket

    2023-12-07 20:32:07       31 阅读
  7. <span style='color:red;'>WebSocket</span>

    WebSocket

    2023-12-07 20:32:07      28 阅读
  8. <span style='color:red;'>WebSocket</span>

    WebSocket

    2023-12-07 20:32:07      29 阅读
  9. <span style='color:red;'>websocket</span>

    websocket

    2023-12-07 20:32:07      14 阅读
  10. <span style='color:red;'>websocket</span>

    websocket

    2023-12-07 20:32:07      16 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-07 20:32:07       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-07 20:32:07       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-07 20:32:07       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-07 20:32:07       18 阅读

热门阅读

  1. Django回顾【五】

    2023-12-07 20:32:07       28 阅读
  2. linux向日葵开机自启动

    2023-12-07 20:32:07       43 阅读
  3. C++初学者线路图 23年12月

    2023-12-07 20:32:07       40 阅读
  4. vs 一直 正在加载设计器的一种解决方法

    2023-12-07 20:32:07       42 阅读
  5. linux rsync 和scp区别

    2023-12-07 20:32:07       36 阅读
  6. Perplexity 推出全新大型在线语言模型

    2023-12-07 20:32:07       41 阅读
  7. Centos7部署NFS

    2023-12-07 20:32:07       47 阅读
  8. Linux:/dev/mapper/centos-root 100%问题

    2023-12-07 20:32:07       34 阅读
  9. Android 透明度颜色值对照表

    2023-12-07 20:32:07       42 阅读
  10. 9月6日,星期三,每日早报简报微语报早读分享

    2023-12-07 20:32:07       34 阅读
  11. Flink入门之部署(二)

    2023-12-07 20:32:07       48 阅读