Spring Boot

WebSocket初识及练习

2018-10-23  本文已影响0人  飞逝1

什么是WebSocket?

为什么会出现WebSocket?

首先我们要了解另一个通信协议:HTTP协议。
HTTP 协议是一种无状态的、无连接的、单向的应用层协议。它采用了请求/响应模型。通信请求只能由客户端发起,服务端对请求做出应答处理。
HTTP协议有一个缺点,那就是无法实现服务器主动向客户端发起消息。
在这个信息千变万化的时代,HTTP协议的缺点无法使服务器端及时推送最新消息给客户端,大多数 Web 应用程序将通过频繁的异步JavaScript和XML(AJAX)请求实现长轮询。轮询的效率低,非常浪费资源(因为必须不停连接,或者 HTTP 连接始终打开)。
这时候,WebSocket就出现了。WebSocket 连接允许客户端和服务器之间进行全双工通信,以便任一方都可以通过建立的连接将数据推送到另一端。WebSocket 只需要建立一次连接,就可以一直保持连接状态。这相比于轮询方式的不停建立连接显然效率要大大提高。

WebSocket属性,事件

属性事件.png

WebSocket方法

方法.png

下面,我将用一个小练习来展示一下WebSocket在SpringBoot中的使用

首先,目录结构


目录结构.png
      <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>
/**
 * WebSocket服务端
 */
@ServerEndpoint("/websocket")
@Component
public class WebSocketServer {
    private static int onlineCount = 0;
    //一个集合,用来存放所有客户端对象
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
    private Session session;

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();//在线数加1
        System.out.println("有新窗口开始监听,当前在线人数为" + getOnlineCount());
        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            System.out.println("WebSocket IO异常");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
        System.out.println("有连接关闭!当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("收到客户端的信息:" + message);
        //群发消息
        for (WebSocketServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }


    /**
     * 群发自定义消息
     */
    public static void sendInfo(String message) throws IOException {
        System.out.println("推送消息内容:" + message);
        for (WebSocketServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                continue;
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}
@Configuration
public class WebSocketConfig {

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

}
@RestController
public class WebSocketController {

    //推送数据接口
    @RequestMapping("/socket/push")
    public String pushMsg(String message) {
        try {
            WebSocketServer.sendInfo(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "success";
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket练习</title>
</head>
<style>
    body {
        text-align: center;
    }
    .radio-area{
        width: 500px;
        height: 500px;
        border-color: black;
        border-style: solid;
        border-width: 1px;
        margin: 0 auto;
    }
    .mes {
        width: 500px;
        height: 30px;
        margin: 20px auto;
    }
    .input-box {
        border-color: black;
        border-style: solid;
        border-width: 1px;
        height: 30px;
        width: 400px;
        float: left;
    }
    .send {
        float: right;
        border-radius: 5px;
        font-size: 18px;
    }
</style>
<body>
<h2>客户端</h2>
<div class="radio-area" id="show">

</div>
<div class="mes">
    <input class="input-box" id="input-box">
    <button value="发送" class="send" onclick="sendMes()" id="btn">发送</button>
</div>
<script src="../js/jquery-3.1.1.js" type="text/javascript" charset="utf-8"></script>
<script>
    var socket;
    var message = document.getElementById("input-box");
    var btn_send = document.getElementById("btn");
    var show_box = document.getElementById("show");
    if (typeof(WebSocket) == "undefined") {
        console.log("您的浏览器不支持WebSocket");
    } else {
        console.log("您的浏览器支持WebSocket");

        //实现化WebSocket对象,指定要连接的服务器地址与端口建立连接
        socket = new WebSocket("ws://localhost:8080/websocket");

        //打开事件
        socket.onopen = function () {
            console.log("Socket已打开");
            btn_send.onclick = function () {
                console.log(message);
                //下面这句话是往服务器发送消息
                socket.send("这是来自客户端的消息:" + message.value);
            };
        };

        //获得消息事件
        socket.onmessage = function (msg) {
            var li_eme = document.createElement("li");
            li_eme.innerHTML = msg.data;
            show_box.appendChild(li_eme);
            //控制台打印消息
            console.log(msg.data);
        };

        //关闭事件
        socket.onclose = function () {
            console.log("Socket已关闭");
        };

        //发生了错误事件
        socket.onerror = function () {
            alert("Socket发生了错误");
        }
    }
</script>
</body>

</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>服务器端</title>
</head>
<style>
</style>
<body>
<h1>server</h1>
<form id="login" action="/socket/push" method="get">
    <label>message
        <input id="msg" type="text" name="message" style="width:215px;" />
    </label>
    <br>
    <input type="submit" id="btn"/>
</form>
</body>
</html>

最终展示界面

参考信息

https://www.cnblogs.com/jingmoxukong/p/7755643.html
https://www.cnblogs.com/bianzy/p/5822426.html

上一篇下一篇

猜你喜欢

热点阅读