websocket + java 一对一聊天和群聊

本文介绍了WebSocket协议的基本概念和特点,如建立在TCP基础上、与HTTP的兼容性、双向通信等。并详细展示了使用Spring Boot实现WebSocket的步骤,包括后台和前端的代码示例,涉及连接建立、消息收发、错误处理等关键方法。最后,总结了WebSocket服务器端的注解及其回调方法的作用。

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

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

简介

WebSocket 协议在2008年诞生,2011年成为国际标准。所有浏览器都已经支持了。

它的最大特点就是,服务器可以主动向客户端推送信息,客户端也可以主动向服务器发送信息,是真正的双向平等对话,属于服务器推送技术的一种。

一、WebSocket是什么?

它是一种网络通信协议,是HTML5开始提供的一种在单个TCP连接上进行双向通信的协议。

其他特点包括:

(1)建立在 TCP 协议之上,服务器端的实现比较容易。
(2)与 HTTP 协议有着良好的兼容性。默认端口也是80和443,并且握手阶段采用 HTTP 协议,因此握手时不容易屏蔽,能通过各种 HTTP 代理服务器。
(3)数据格式比较轻量,性能开销小,通信高效。
(4)可以发送文本,也可以发送二进制数据。
(5)没有同源限制,客户端可以与任意服务器通信。
(6)协议标识符是ws(如果加密,则为wss),服务器网址就是 URL。

二、使用步骤

1.引入库

代码如下(示例):

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

2.后台代码

代码如下(示例):



import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint(value = "/webSocket/{userID}")
public class WebSocketServer {

    /**
     * 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
     */
    private static int onlineCount = 0;

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

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

    /**
     * concurrent包的线程安全Set,用来存放每个客户端对应的WebSocketServer对象。
     */
    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();
    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(@PathParam("userID") String userID, Session session) {
        System.out.println("userID="+userID);
        this.session = session;
        //加入set中
        webSocketSet.add(this);
        sessionPools.put(userID,session);
        //在线数加1
        addOnlineCount();
        System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
        try {
            sendMessage(session,"当前在线人数为" + getOnlineCount());
        } catch (IOException e) {
            System.out.println("IO异常");
        }
    }

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

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        System.out.println("来自客户端的消息:" + message);
        JSONObject jsonObject = JSONObject.parseObject(message);
        if (jsonObject.containsKey("toUserId") && !"".equals(jsonObject.get("toUserId"))){
            // 私信
            System.out.println("私信");
            sendInfo((String) jsonObject.get("toUserId"),(String) jsonObject.get("contentText"));
        }else{
            //群发消息
            for (WebSocketServer item : webSocketSet) {
                System.out.println("item="+item.session);
                // 是自己就不用发了
                if (!item.session.equals(session)){
                    item.sendMessage(item.session ,(String) jsonObject.get("contentText"));
                }
            }
        }
    }

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

    public void sendMessage(Session session, String message) throws IOException {
        if (session!=null){
            synchronized (session) {
                session.getBasicRemote().sendText(message);
            }
        }
    }

    /**
     * 私信
     */
    public void sendInfo(String userID, String message) throws IOException {
        Session session = sessionPools.get(userID);
        System.out.println(session);
        if (sessionPools.get(userID) != null){
            sendMessage(session, message);
        }else {
            System.out.println("用户"+userID+"不在线");
        }
    }

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

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

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


// 启动类

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

@Configuration 
public class WebConfig {

    @Bean
    public ServerEndpointExporter serverEndpointConfigurator(){
        System.out.println("webSocket启动了");
        return new ServerEndpointExporter();
    }
}

该处使用的url网络请求的数据。


2.前端代码

代码如下(示例):



<!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">1</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:8080/webSocket/1");
    }
    else {
        alert('当前浏览器 Not support websocket')
    }
    //发送消息
    function send() {
        var message = document.getElementById('text').value;//要发送的消息内容
        document.getElementById('message').innerHTML += ("发送人:"+userno+"---"+message) + '<br/>';
        var ToSendUserno=document.getElementById('usernoto').value; //接收人编号:4567
        message='{"contentText":"'+message+'","toUserId":"'+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>

websocket = new WebSocket(“ws://localhost:8080/webSocket/1”);
里面的端口号设置成自己的,不然会链接不成功。
ws://localhost:8080/webSocket/1
1 就是index.html的标识,可以吧这个html复制两个第二个html的1要改成2,以此类推。


总结

@ServerEndpoint(“/webSocket”) 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端。
@OnOpen 连接建立成功调用的方法
@OnClose 连接关闭调用的方法
@OnMessage 收到客户端消息后调用的方法
@OnError 有异常的时候被调用
@BeforeHandshake 当有新的连接进入时,对该方法进行回调 注入参数的类型:Session、HttpHeaders…
@OnBinary 当接收到二进制消息时,对该方法进行回调 注入参数的类型:Session、byte[]
@OnEvent 当接收到Netty的事件时,对该方法进行回调 注入参数的类型:Session、Object

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值