idea+springboot+websocket实现简单的单对单交流

本文详细介绍如何使用Spring Boot框架搭建WebSocket服务器,实现点对点通信功能。文章涵盖后端配置、前端页面设计及交互逻辑,同时展示了多客户端间如何进行有效通信。

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

1.建立项目

依赖已经自动配置好了,就不用添加了。

2、后端

建立这两个类,代码如下:

package com.example.websockettest;
//WebSocketConfig
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
//首先要注入ServerEndpointExporter,这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint。
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

}

 

package com.example.websockettest;

import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;

/**
 * @ServerEndpoint 注解是一个类层次的注解,它的功  能主要是将目前的类定义成一个websocket服务器端,
 * 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
 */
@ServerEndpoint("/websocket")
@Component
public class WebSocketTest {
    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    //用来存放每个客户端对应的MyWebSocket对象。
    //使用Map来存放,其中Key可以为用户标识
    private static HashMap<String,WebSocketTest> webSocketMap =new HashMap<>();
    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;

    /**
     * 连接建立成功调用的方法
     * @param session  可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
     */
    @OnOpen
    public void onOpen(Session session) throws IOException {
        this.session = session;
        webSocketMap.put(session.hashCode()+"",this); //加入map中
        System.out.println("这个客户端的用户名:" + session.hashCode());
        this.sendMessage("你分配的用户名:" + session.hashCode());
        addOnlineCount();           //在线数加1
        System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
    }

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

        webSocketMap.remove(this);//从map中删除
        subOnlineCount();           //在线数减1
        System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());

    }

    /**
     * 收到客户端消息后调用的方法
     * @param message 客户端发送过来的消息
     * @param session 可选的参数
     */
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        
        //发送的用户号就是session.hashcode(),可以再加个map继续映射
        //通过#*#*这个字符串来分割消息的组成,我随意设定的
        int pos=message.indexOf("#*#*");
        String realmessage=message.substring(0,pos);
        //这个4是因为#*#*这个字符串长度为4
        String realuser=message.substring(pos+4,message.length());
        System.out.println("来自客户端的消息:" + realmessage);
        //
        WebSocketTest item=webSocketMap.get(realuser);
        item.sendMessage(realmessage);

    }

    /**
     * 发生错误时调用
     * @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.session.getBasicRemote().sendText(message);
        //this.session.getAsyncRemote().sendText(message);
    }

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

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

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

3.前端


<!DOCTYPE HTML>
<html>
<head>
	<meta charset="UTF-8">
    <title>My WebSocket</title>
</head>

<body>
WebSocket<br/>
<input id="text" type="text" placeholder="消息"/>
<input id="user" type="text" placeholder="用户名"/>
<button onclick="send()">发送消息</button> 
<button onclick="closeWebSocket()">关闭</button>
<div id="message">
</div>
</body>

<script type="text/javascript">
    var websocket = null;

    //判断当前浏览器是否支持WebSocket
    if('WebSocket' in window){
        websocket = new WebSocket("ws://localhost:8080/websocket");
    }
    else{
        alert('Not support websocket')
    }

    //连接发生错误的回调方法
    websocket.onerror = function(){
        setMessageInnerHTML("连接发生错误");
    };

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

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

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

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

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

    //关闭连接
    function closeWebSocket(){
        websocket.close();
    }

    //发送消息
    function send(){
        var message = document.getElementById('text').value;
        var user = document.getElementById('user').value;
        
        websocket.send(message+"#*#*"+user);
    }
</script>
</html>

4.效果演示

 

理论上可以开多个客户端,各自点对点通信。

感觉有点类似邮件

本篇博客的大部分内容转载自:https://www.cnblogs.com/xdp-gacl/p/5193279.html

他实现的是消息群发的功能,我再次基础上,改动了下变成这样的,服务器当作消息的中转站,如果有更好的想法,欢迎交流。

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值