java使用WebSocket

1、业务需求:在学生进行单词练习的页面,左侧有一个全班学生的回答正确单词数量的排名,要求实时的更新,之前使用页面每隔1秒向后台发送请求获取的方式,但是因为之前有其他的轮询,对服务造成的压力太大,所以决定使用websocket,在用户完成一个单词保存时,服务器返回排名列表。

2、WebSocket介绍:

WebSocket是基于TCP的一种新的网络协议,最大的特点就是实现了浏览器与服务器全双工(full-duplex)通信,2011年WebSocket协议被接受为国际标准
HTML5开始提供WebSocket协议的支持。

什么叫全双工通讯? 其实就是通信的双方都可以主动发送消息,又可以接受消息.WebSocket协议之前,全双工通信是通过多个http链接来实现,这导致了效率低下。WebSocket的出现就是为了解决这个问题。

3、实现步骤:

1)准备:

测试环境:spingBoot + tomcat7 + jdk8 + chrome浏览器

webSocket的依赖:

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

2)后台代码

package com.yanzhiyi.manager.websocket;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * FileName: WebSocketServer2
 * Author:   xuan zongjun
 * Date:     2019/8/7 9:21
 * Description: webSocket测试
 */
@Component
@ServerEndpoint("/websocket2/{userno}")
public class WebSocketServer2 {

    private static int onlineCount = 0;
    private static ConcurrentHashMap<String, WebSocketServer2> webSocketSet = new ConcurrentHashMap<String, WebSocketServer2>();
    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session WebSocketsession;

    //当前发消息的人员编号
    private String userno = "";

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

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

    public static synchronized void subOnlineCount() {
        WebSocketServer2.onlineCount--;
    }

    @OnOpen
    public void onOpen(@PathParam(value = "userno") String param, Session WebSocketsession, EndpointConfig config) {
        System.out.println( param );
        userno = param;//接收到发送消息的人员编号
        this.WebSocketsession = WebSocketsession;
        webSocketSet.put( param, this );//加入map中
        addOnlineCount();           //在线数加1
        System.out.println( "有新连接加入!当前在线人数为" + getOnlineCount() );
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     * @param session 可选的参数
     */
    @SuppressWarnings("unused")
// @OnMessage
    public void onMessage(String message, Session session) {
        String[] sendMessage = message.split( "[|]" );
        System.out.println( "来自客户端的消息:" + message );
        String[] user = message.split( "[|]" );
        //群发消息
        if (user.length == 1) {
            sendAll( message );
        } else {
            //给指定的人发消息
            sendToUser( message );
        }
    }

    /**
     * 给所有人发消息
     *
     * @param message
     */

    public void sendAll(String message) {
        System.out.println( "给所人发信息" );
        String sendMessage = message.split( "[|]" )[0];
        //遍历HashMap
        for (String key : webSocketSet.keySet()) {
            System.out.println( "当前的key" + webSocketSet.keySet() );
            try {
                //判断接收用户是否是当前发消息的用户
                if (!userno.equals( key )) {
                    System.out.println( "userno" + userno );
                    webSocketSet.get( key ).sendMessage( "用户" + userno + ": 广播" + " <br/> " + sendMessage );
                    System.out.println( "key = " + key );
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 给指定的人发送消息
     *
     * @param message
     */
    @OnMessage
    public void sendToUser(String message) {
        System.out.println( "给指定人发信息" );
        String sendUserno = message.split( "[|]" )[1];
        String sendMessage = message.split( "[|]" )[0];
        try {
            System.out.println( "webSocketSet.get(sendUserno)" + webSocketSet.get( sendUserno ) );
            if (webSocketSet.get( sendUserno ) != null) {
                List<String> list = new ArrayList();
                list.add( "lisi" );
                list.add( "wangwu" );
                webSocketSet.get( sendUserno ).sendMessage( "用户" + userno + ": 广播" + " <br/> " + list.toString() );
            } else {
                System.out.println( "当前用户不在线" );
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {

        if (!userno.equals( "" )) {
            webSocketSet.remove( userno );  //从set中删除
            subOnlineCount();           //在线数减1
            System.out.println( "有一连接关闭!当前在线人数为" + getOnlineCount() );
        }
    }

    /**
     * 获取当前时间
     *
     * @return
     */
    private String getNowTime() {
        Date date = new Date();
        DateFormat format = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
        String time = format.format( date );
        return time;
    }

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

    /**
     * 这个方法与上面几个方法不一样。没有用注解,是根据自己需要添加的方法。
     *
     * @param message
     * @throws IOException
     */
    public void sendMessage(String message) throws IOException {
        this.WebSocketsession.getBasicRemote().sendText( message );
        //this.session.getAsyncRemote().sendText(message);
    }

    public void setUserno(String userno) {
        this.userno = userno;
    }


}

3)前台代码:

<!DOCTYPE html>
<html >
<head>
    <meta charset="UTF-8">
    <title>Java后端WebSocket的Tomcat实现</title>
</head>
<body>
    Welcome<br/><input id="text" type="text"/>
    <button onclick="send()">发送消息</button>
    <hr/>
    <!--userno:发送消息人的编号-->
    发送人:<div id="userno">4567</div>
    接收人:<input type="text" id="usernoto"><br>
    <button onclick="closeWebSocket()">关闭WebSocket连接</button>
    <hr/>
    <div id="message"></div>
</body>

<script type="text/javascript">
    var websocket = null;
    var userno=document.getElementById('userno').innerHTML;
    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://localhost:8089/websocket2/"+userno);
    }
    else {
        alert('当前浏览器 Not support websocket')
    }
    //发送消息
    function send() {
        var message = document.getElementById('text').value;//要发送的消息内容
        document.getElementById('message').innerHTML += ("发送人:"+userno+'<br/>'+"---"+message) + '<br/>';
        document.getElementById('message').style.color="red";
        var ToSendUserno=document.getElementById('usernoto').value; //接收人编号:4567
        message=message+"|"+ToSendUserno//将要发送的信息和内容拼起来,以便于服务端知道消息要发给谁
        websocket.send(message);
    }
    //连接发生错误的回调方法
    websocket.onerror = function () {
        setMessageInnerHTML("WebSocket连接发生错误");
    };

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

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

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

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

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

    //关闭WebSocket连接
    function closeWebSocket() {
        websocket.close();
    }
</script>
</html>

参考来源:https://blog.csdn.net/qq_33842966/article/details/79930160
 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值