springboot+websocket实现简单的在线聊天功能

博客展示了Java实现的效果及逻辑,包含客户端html代码,创建了名为xiaoMing和xiaoHua的两个客户端,还给出了转载来源。

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

效果如下:

 

 

java实现逻辑:

1.引入maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2.创建一个服务端
package com.example.demo.controller;

import org.springframework.web.bind.annotation.RestController;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/websocket/{name}")
@RestController
public class WebSocketServer {

    //存储客户端的连接对象,每个客户端连接都会产生一个连接对象
    private static ConcurrentHashMap<String,WebSocketServer> map=new ConcurrentHashMap();
    //每个连接都会有自己的会话
    private Session session;
    private String name;
    @OnOpen
    public void open(@PathParam("name") String name, Session session){
        map.put(name,this);
        System.out.println(name+"连接服务器成功");
        System.out.println("客户端连接个数:"+getConnetNum());

        this.session=session;
        this.name=name;
    }
    @OnClose
    public void close(){
        map.remove(name);
        System.out.println(name+"断开了服务器连接");
    }
    @OnError
    public void error(Throwable error){
        error.printStackTrace();
        System.out.println(name+"出现了异常");
    }
    @OnMessage
    public void getMessage(String message) throws IOException {
        System.out.println("收到"+name+":"+message);
        System.out.println("客户端连接个数:"+getConnetNum());

        Set<Map.Entry<String, WebSocketServer>> entries = map.entrySet();
        for (Map.Entry<String, WebSocketServer> entry : entries) {
            if(!entry.getKey().equals(name)){//将消息转发到其他非自身客户端
                entry.getValue().send(message);

            }
        }
    }

    public void send(String message) throws IOException {
        if(session.isOpen()){
           session.getBasicRemote().sendText(message);
        }
    }

    public int  getConnetNum(){
        return map.size();
    }
}
3.一个配置类
@Configuration
public class WebSocketConfig {

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

//客户端html代码,此处创建2个客户端,一个叫xiaoMing一个叫xiaoHua

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>当前用户xiaoMing</title>
</head>
<style>
    #message{
        width: 50%;
        height: 500px;
        border: 1px solid black;
        background-color: darkgray;

    }

    #inputVal{
        width: 50%;
    }
    input{
        width: 92%;
    }
</style>
<body>
<h1>当前用户xiaoMing</h1>
<div id="message">

</div>
<div id="inputVal">
    <input type="text" name="text">
    <button onclick="send()">发送</button>
</div>

<script>
    var messageEl=document.getElementById("message");
    var inputEl=document.getElementsByTagName("input")[0];
    var websocket=null;
    if('WebSocket' in window){
        websocket=new WebSocket("ws:localhost:2300/websocket/xiaoMing");
    }else {
        alert("浏览器不支持");

    }
    websocket.onopen=function () {
        console.log("webscoket已经连接成功");
        addMessage("webscoket已经连接成功");

    };
    websocket.onclose=function () {
        console.log("webscoket连接失败");
        addMessage("webscoket连接失败");
    };
    websocket.onmessage=function (event) {
        addMessage(event.data);
    };
    websocket.onerror=function () {
        console.log("webscoket连接失败");
        addMessage("webscoket连接失败");
    };
    function addMessage(message) {
        messageEl.innerHTML+=message+"</br>";
    }
    
    function send() {
        websocket.send("xiaoMing:"+inputEl.value);
        messageEl.innerHTML+="我:"+inputEl.value+"</br>";
    }


</script>

</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>当前用户xiaoHua</title>
</head>
<style>
    #message{
        width: 50%;
        height: 500px;
        border: 1px solid black;
        background-color: darkgray;
    }

    #inputVal{
        width: 50%;
    }
    input{
        width: 92%;
    }
</style>
<body>
<h1>当前用户xiaoHua</h1>
<div id="message">

</div>
<div id="inputVal">
    <input type="text" name="text">
    <button onclick="send()">发送</button>
</div>

<script>
    var messageEl=document.getElementById("message");
    var inputEl=document.getElementsByTagName("input")[0];

    var websocket=null;
    if('WebSocket' in window){
        websocket=new WebSocket("ws:localhost:2300/websocket/xiaoHua");
    }else {
        alert("浏览器不支持");

    }
    websocket.onopen=function () {
        console.log("webscoket已经连接成功");
        addMessage("webscoket已经连接成功");

    };
    websocket.onclose=function () {
        console.log("webscoket连接失败");
        addMessage("webscoket连接失败");
    };
    websocket.onmessage=function (event) {
        addMessage(event.data);
    };
    websocket.onerror=function () {
        console.log("webscoket连接失败");
        addMessage("webscoket连接失败");
    };
    function addMessage(message) {
        messageEl.innerHTML+=message+"</br>";
    }

    function send() {
        websocket.send("xiaoHua:"+inputEl.value);
        messageEl.innerHTML+="我:"+inputEl.value+"</br>";
    }


</script>

</body>
</html>

 

转载于:https://www.cnblogs.com/yangxiaohui227/p/11077172.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值