WebSocket

简介

WebSocket 是 HTML5 开始提供的一种在单个 TCP 连接上进行全双工通讯的协议。

HTTP协议在浏览器和服务器交互时,在完成一次数据传输后,就会断开。并且只能由浏览器向服务器发出请求,因此在需要实时更新时,只能利用Ajax进行轮询,频繁连接服务器。

webSocket则只需要进行一次连接后,就可以一直相互发送数据。

1607586397190.png

其中websocket中http连接和普通的http连接有所不同,

客户端向服务器发出HTTP请求:

GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
Origin: http://example.com

其中关注:

Upgrade: websocket
Connection: Upgrade
这是告诉服务器,升级为websocket请求

服务器向客户端回复

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat

这样就完成了websocket连接。

简易聊天室

简易聊天室——大体流程:

(1)用户输入用户名和密码,点击登录

(2)后台UserController.login将用户名存入HttpSession,跳转到message.html页面

(3)进入message.html页面,建立websocket连接,后台响应onOpen事件,从EndpointConfig中取出HTTPSession,然后在从httpSession中取出用户名,然后以用户名为key,该websocket对象为值,存入onLineUsers中。

(4)用户输入要发送人的用户名和消息,点击发送。ajax带着表单信息请求到后台sendMessage接口,后台根据要发送的用户名,在onLineUsers中取出相应的websocket对象,进行消息发送。

(5)被发送用户,响应onmessage事件,将消息弹窗显示

服务器端

依赖:

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>
    </dependencies>

首先,新建webSocket的配置类:

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

/**
 * @author yuanwei
 * @date 2020/12/8 17:21
 * @description
 */
@Component
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
}

接着构建websocket事件类

import com.example.websocket.config.GetHttpSessionConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author yuanwei
 * @date 2020/12/8 18:01
 * @description
 */
@Component
@ServerEndpoint(value="/webSocket",configurator = GetHttpSessionConfig.class)
@Slf4j
public class WebSocket {

    private Session session;

    private static Map<String,WebSocket> onLineUsers=new ConcurrentHashMap<>();

    private HttpSession httpSession;

    @OnOpen
    public void onOpen(Session session, EndpointConfig endpointConfig){
        this.session = session;
        this.httpSession = (HttpSession) endpointConfig.getUserProperties().get(HttpSession.class.getName());
        onLineUsers.put((String)this.httpSession.getAttribute("user"),this);
        log.info("【websocket消息】有新的连接,总数:{}",onLineUsers.size());
    }

    @OnClose
    public void onClose(EndpointConfig endpointConfig){
        onLineUsers.remove(this.httpSession.getAttribute("user"));
        log.info("【websocket消息】连接断开,总数:{}",onLineUsers.size());
    }

    @OnMessage
    public void onMessage(String message){
        log.info("【websocket消息】收到客户端发来的消息:{}",message);
    }

    public void sendMessage(String toUsername,String message){
        try{
            if(onLineUsers.containsKey(toUsername)){
                onLineUsers.get(toUsername).session.getBasicRemote().sendText(message);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}

UserController:只为区分不同用户,不进行校验用户名和密码

@Controller
public class UserController {

    @PostMapping("/login")
    public String login(String name, String password, HttpSession session){
        session.setAttribute("user",name);
        return "./message.html";
    }
}

WebSocketController:用于浏览器端发送消息

import com.example.websocket.service.WebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author yuanwei
 * @date 2020/12/9 9:52
 * @description
 */
@RestController
public class WebSocketController {

    @Autowired
    private WebSocket webSocket;

    @PostMapping("/sendMessage")
    public void sendMessage(String toUsername,String message){
        try{
            webSocket.sendMessage(toUsername,message);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

GetHttpSessionConfig:获取HttpSession,并将之存储在ServerEndpointConfig,以供websocket获取httpSession中的用户名。(如不需该操作,可省略)

import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;

/**
 * @author yuanwei
 * @date 2020/12/10 17:22
 * @description
 */
public class GetHttpSessionConfig extends ServerEndpointConfig.Configurator {

    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        HttpSession httpSession = (HttpSession) request.getHttpSession();
        sec.getUserProperties().put(HttpSession.class.getName(),httpSession);
    }
}

浏览器端

登录页面,只为其用户名

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <!-- 新 Bootstrap 核心 CSS 文件 -->
    <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">

    <!-- jQuery文件。务必在bootstrap.min.js 之前引入 -->
    <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>

    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
    <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <title>Title</title>
</head>
<body>
    <div>
        <form class="form-horizontal" role="form" action="/login" method="post">
            <div class="form-group">
                <label for="name" class="col-sm-2 control-label">名字</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" id="name" name="name" placeholder="请输入名字">
                </div>
            </div>
            <div class="form-group">
                <label for="password" class="col-sm-2 control-label">密码</label>
                <div class="col-sm-10">
                    <input type="password" class="form-control" id="password" name="password" placeholder="请输入姓">
                </div>
            </div>
            <div class="form-group">
                <div class="col-sm-offset-2 col-sm-10">
                    <button type="submit"  class="btn btn-default">登录</button>
                </div>
            </div>
        </form>
    </div>

</body>

</html>

发送消息页面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!-- 新 Bootstrap 核心 CSS 文件 -->
    <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">

    <!-- jQuery文件。务必在bootstrap.min.js 之前引入 -->
    <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>

    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
    <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
    <form role="form" action="/sendMessage" id="form1" method="post">
        <div class="form-group">
            <label for="firstname" class="col-sm-2 control-label">名字</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" name="toUsername" id="firstname" placeholder="请输入名字">
            </div>
        </div>
        <div class="form-group">
            <label for="message">文本框</label>
            <textarea class="form-control" name="message" id="message" rows="3"></textarea>
        </div>
        <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
                <button type="button" id="mybutton"  class="btn btn-default">发送</button>
            </div>
        </div>
    </form>
</body>
<script>
    var websocket = null;
    if('WebSocket' in window){
        websocket = new WebSocket("ws://localhost:8080/webSocket");
    }else{
        alert("该浏览器不支持webSocket!");
    }

    websocket.onopen = function (event) {
        console.log("建立连接");
    }

    websocket.onclose = function (event) {
        console.log("连接关闭");
    }

    websocket.onmessage = function (event) {
        console.log("收到消息:"+event.data);
        alert(event.data)
    }
    $("#mybutton").click(function(e){
        $.ajax({
            //几个参数需要注意一下
            type: "POST",//方法类型
            dataType: "json",//预期服务器返回的数据类型
            url: "/sendMessage" ,//url
            data: $('#form1').serialize()
        });
    });
</script>
</html>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容