Java WebSocket介绍

本文介绍了WebSocket作为消息推送的高效解决方案,对比了轮询和长连接的优缺点。通过一个具体的WebSocket实现实例,展示了如何在Spring框架下配置和使用WebSocket,包括连接建立、消息收发和异常处理。此外,还提供了前端页面与WebSocket交互的代码示例,以及服务运行后的测试场景。总结了WebSocket在实际应用中的关键点和扩展性需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言
日常工作中,大家会接触到websocket和socket,但有时分不清二者的用处和区别,这篇文章介绍websockect的用处和实现。

一、消息推送的选型对比
1.1 轮询
介绍:客户端定时向服务端发送ajax请求,服务器收到请求后立即返回并关闭连接。
优点:后端编写程序较容易。
缺点:TCP的建立和关闭浪费时间和带宽及服务器资源。
1.2 长连接
介绍:发起HTTP 请求,创建一个TCP连接,当前HTTP 的请求发送并接收完,TCP 连接并不关闭,如果还有请求,可以直接在这个TCP连接上继续发送(不需要经过三次握手,四次挥手的连接消耗)。
优点:减少服务端和客户端的连接数,消息即时到达,没有无用请求。
缺点:当客户端越来越多时,服务器压力较大。
1.3 websocket
介绍:websocket是基于TCP的协议,使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在 WebSocket API 中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。(更好的代替轮询和长连接)

二、WebSocket的实现
2.1引入依赖包

<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-websocket</artifactId>
   <version>5.1.9.RELEASE</version>
</dependency>

2.2 websocket实现

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yoka.framework.constants.enums.StatusCode;
import com.yoka.framework.entity.exception.CaseServerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

/**
 * @author:jack
 * @date 2021/9/9 19:59
 * @des:todo
 * @ServerEndpoint:userId为当前会话窗口的用户id
 */
@Component
@ServerEndpoint(value = "/websocket/{userId}")
public class WebSocketTest {


    /**
     * 日志
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketTest.class);

    /**
     * 每个socket维护的信息
     * @onOpen
     * @onMesssage
     * @onError
     * @onClose
     */
    private String userId;
    //和客户端的连接会话
    private Session session;


    /**
     * 成功建立调用
     * @param userId
     * @param session
     */
    @OnOpen
    public void onOpen(@PathParam(value = "userId") String userId,
                       Session session){
        try {
            LOGGER.info("-----进入ws----");
            this.userId = userId;
            this.session = session;

            //新用户进入,用户列表加入该用户
            WebSocketDTO.userList.add(userId);
            //在线人数+1
            WebSocketDTO.onlineCountAdd();
            //当前websocket对象+1
            WebSocketDTO.webSocketTestsAdd(this);
            LOGGER.info("用户:" + userId + "成功加入,当前用户数:" + WebSocketDTO.getOnlineCount());
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * 关闭调用
     * @param userId
     */
    @OnClose
    public void onClose(@PathParam(value = "userId") String userId){

        //用户退出,websocket对象列表删除当前对象
        WebSocketDTO.webSocketTestsDe(this);
        //在线用户数减1
        WebSocketDTO.onlineCountDe();
        LOGGER.info("用户:" + userId + "退出聊天,当前用户数:" + WebSocketDTO.getOnlineCount());

    }

    /**
     * 处理客户端送过来的消息
     * @param userId
     * @param message
     */
    @OnMessage(maxMessageSize = 1024*1024)
    public void onMessage(@PathParam(value = "userId") String userId,
                          String message) {
        LOGGER.info("前端传入的消息:"+message);
        if (message == "" || message == null){
            throw new CaseServerException("不支持输入为空",StatusCode.WS_UNKNOWN_ERROR);
        }
        try {
            sendInfo(message,userId);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * 处理异常消息
     * @param session
     * @param e
     */
    @OnError
    public void onError(Session session, Throwable e) {
        LOGGER.info(Thread.currentThread().getName() + ": [websocket-onError 会话出现异常]当前session={}, 原因={}", session.getId(), e.getMessage());
    }


    /**
     * 用户发送消息
     * @param message
     * @param userId
     */
    public void sendInfo(String message,String userId){
        JSONObject content = new JSONObject();//实际发送内容
        for (WebSocketTest item : WebSocketDTO.getWebSocketTests()){
            //排除消息发送给自己
            if (item.userId != userId){
                content.put("time", TimeUtil.currentTime());
                content.put("sendUser",userId);
                content.put("message",message);
            }
            item.sendMessage(JSON.toJSONString(content));
        }
    }

    /**
     * 发送消息内容
     * @param message
     */
    public void sendMessage(String message){
        this.session.getAsyncRemote().sendText(message);
    }
}

2.3 WebSocketDTO对公共数据进行维护

public class WebSocketDTO {

    //存放WebSocketTest对象
    static List webSocketTests = new ArrayList();

    //当前在线用户数
    static int onlineCount = 0;

    //聊天室所有用户
    static List userList = new ArrayList();

    //在线用户数新增
    public static void onlineCountAdd(){
        onlineCount++;
    }

    //用户离开聊天室
    public static void onlineCountDe(){
        onlineCount--;
    }

    //新建websocket连接
    public static void webSocketTestsAdd(Object webSocketTest){
        webSocketTests.add(webSocketTest);
    }

    //关闭socket连接
    public static void webSocketTestsDe(WebSocketTest webSocketTest){
        webSocketTests.remove(webSocketTest);
    }

    public static void userListAdd(String userId){
        userList.add(userId);
    }
    public static void deuserList(String userId){
        userList.remove(userId);
    }

    public static int getOnlineCount() {
        return onlineCount;
    }

    public static void setOnlineCount(int onlineCount) {
        WebSocketDTO.onlineCount = onlineCount;
    }

    public static List<WebSocketTest> getWebSocketTests() {
        return webSocketTests;
    }

    public static void setWebSocketTests(List webSocketTests) {
        WebSocketDTO.webSocketTests = webSocketTests;
    }
    
}

2.4 前端页面代码展示

//随机生成用户id
if ('WebSocket' in window) {
  var randomUserId = parseInt(Math.random() * 1000000) + "";
  websocket = new WebSocket("ws://localhost:8094/websocket/"+ randomUserId);
} else {
  alert('websocket连接异常')
}

//错误回调
websocket.onerror = function() {
  messageOnPage("error");
};

//连接成功回调
websocket.onopen = function(event) {
  messageOnPage("open");
}

//处理业务的回调方法
websocket.onmessage = function(event) {
  messageOnPage(event.data);
}

//关闭回调
websocket.onclose = function() {
  messageOnPage("close");
}

//关闭websocket连接
window.onbeforeunload = function() {
  websocket.close();
}

2.5 运行服务
浏览器开启多个页面访问:http://localhost:8094/,生成多个会话窗口(不同userId),并发送消息。
请添加图片描述

三、小结
文章简单介绍websocket的使用,实际业务中消息体可能是文件,音频,图片等,需要在onMessage方法中进行对应的处理,以及接收人可以是指定的,需要进行遍历判断。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值