0
点赞
收藏
分享

微信扫一扫

WebSocket的使用

WebSocket的介绍 对于WebSocket 不了解的同学,可以去参考此文章

说明:基于springboot去实现的

  • @ServerEndpoint 注解将 ChatServer 类作为 WebSocket 服务器端的入口点,定义了一个 /chat 的 WebSocket 端点。
  • @onOpen 链接成功调用
  • @onClose 链接关闭调用
  • @OnError 链接异常调用
  • @OnMessage 收到从服务器中发来的消息

0.依赖包

<!--websocket依赖包-->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

1.配置WebSocket 对象bean

@Configuration
public class WebSocketConfigure {

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

2.代码实现

注册到配置文件中

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

}

3.WebSocket实现

package com.zzy.websocket;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.CopyOnWriteArraySet;
/**
 * zzy
 */
@ServerEndpoint("/websocket/{name}/{password}")
@Component
public class WebSocketServer {

    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<Session> webSocketSet = new CopyOnWriteArraySet<Session>();

    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;

    /**
     * 成功建立连接调用的方法.
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("name") String name, @PathParam("password") String password) {
        System.out.println("服务端接收到消息:");
        System.out.println(name);
        System.out.println(password);
        webSocketSet.add(session);
    }

    /**
     * 连接关闭调用的方法.
     */
    @OnClose
    public void onClose(Session session) {
        webSocketSet.remove(session);
    }

    /*
     * 收到客户端消息后调用的方法.
     */
    @OnMessage
    public String onMessage(String message, Session session) {
        System.out.println(session);
        System.out.println(message);
        return message;
    }

    /**
     * 发生错误时调用.
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("出现问题"+error);
    }

}

3.前端页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
</head>
<style>


    .clearfix {
        zoom: 1;
    }

    .clearfix:after {
        display: block;
        content: '';
        clear: both;
        height: 0;
        visibility: hidden;
    }

    .header, .footer {
        height: 70px;
        text-align: center;
    }

    .content {
        margin: 0 auto;
        width: 1000px;
    }

    .side {
        float: left;
        height: 500px;
        width: 280px;
    }

    .main {
        float: right;
        height: 500px;
        width: 700px;
    }

</style>
<body>

<div class="content clearfix">
    <div class="side">
        <p>聊天列表</p>
        <!--  <div style="width: 100px;height: 200px;outline: 1px darkkhaki solid;"></div>-->
        <div id="ownerchatList" style="width: 200px;height: 300px;border: 1px solid black"></div>
    </div>
    <div class="main">


        <div style="overflow-y:auto; overflow-x:auto; width:400px; height:400px;outline: 1px darkkhaki solid;margin-top: 20px"
             id="message">

        </div>
        <div style="width: 450px;height: 30px;">
            <div style="width: 450px;height: 30px;">
                <input type="text" id="text" style="width: 397px;height: 25px" name="text"/>
                <button onclick="send()" id="btnAdd" >发送</button>

            </div>
        </div>

        <div></div>
    </div>

    <table>
        <tbody id="tbody"></tbody>
    </table>
</div>
<div class="footer">
    <p>消息提醒</p>
    <div id="tixing" style="width: 350px;height: 150px;border: 1px solid black;margin-left: 620px">
    </div>
</div>


<script>
    var websocket = null;
    var name = ''
    var passwords = '123456'
    var serverPaths = 'localhost:8080'
    window.onload = conectWebSocket()
    //连接对象.
    function conectWebSocket() {
        //判断当前的浏览器是否支持websocket.
        if ("WebSocket" in window) {
            url = "ws://" + serverPaths + "/websocket/" + name + "/" + passwords;
            websocket = new WebSocket(url);
        } else {
            alert("Not support websocket");
            return false;
        }
        //连接成功的方法.
        websocket.onopen = function (event) {
            setMessgeHtml("Loc MSG:连接成功");
        }

        //连接关闭.
        websocket.onclose = function (event) {
            setMessgeHtml("Loc MSG:连接关闭");
        }

        //连接异常.
        websocket.onerror = function (event) {
            setMessgeHtml("Loc MSG:连接异常");
        }
        websocket.onmessage = function (event) {
            setMessgeHtml(event.data);
        }
    }

    function closeWebSocket() {
        this.websocket.close();
    }

    function setMessgeHtml(msg) {
        var message = document.getElementById("message");
        message.innerHTML += msg + "<br/>";

    }

    /**
     发送消息.
     前端通过send()方法,将信息发送给服务器,其中将信息用json形式处理。因为一条正常的消息,
     可能是文本,可能是图片,可能是视频,我们必然需要一个type,如果每条消息都要保存进数据库,
     那么这条消息是谁发的,发送给谁,等等一系列字段都需要传入服务端。
     用json序列化,就能很好的保存这些数据。
     */
    function send(){
        var message = document.getElementById("text").value;
        var socketMsg = {'msg':message ,'type':"text"}
        websocket.send(JSON.stringify(socketMsg));//将json对象转换为json字符串.
        $("#text").val("");

    }
</script>
</body>
</html>












举报

相关推荐

0 条评论