Spring Boot使用WebSocket实现群聊

1.通过https://start.aliyun.com创建一个spring boot项目

https://start.aliyun.com

所需依赖:

2.编写代码

目录:

WebMvcConfig,监控用户页面:

package com.example.mywbsk.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

//监控用户页面
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    //注册两个客户端资源名和路径 代表张三和李四分别登录了聊天页面
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/zs").setViewName("zs");
        registry.addViewController("/ls").setViewName("ls");
    }
}

WebSocketConfig,WebSocket核心 存放在spring容器中:

package com.example.mywbsk.config;

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

//WebSocket核心 存放在spring容器中
@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
}

controller,管理员功能:

package com.example.mywbsk.controller;

import com.example.mywbssk.services.WebSocketServer;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;

@RestController
public class controller {
    @Resource
    private WebSocketServer webSocketServer;

    //服务器给某人发送信息
    @RequestMapping(value = "/socket",method = RequestMethod.GET)
    public void singleSocket(@RequestParam("name")String name,@RequestParam("msg")String msg){
        webSocketServer.sendInfo(name,msg);
    }

    //服务器向群体发送信息
    @RequestMapping(value = "/socket/all",method = RequestMethod.GET)
    public void collectiveSocket(@RequestParam("msg")String msg){
        try {
            webSocketServer.onMessage(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

WebSocketServer,websocket服务器:

package com.example.mywbsk.services;

import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

//websocket服务器
@Component
@ServerEndpoint("/socket/{name}")
public class WebSocketServer {
    //原子类 在多线程情况 原子类会自动上锁 记录在线人数
    private static AtomicInteger online = new AtomicInteger();

    //存放每个客户端对当前服务器WebSocket会话对象
    private static Map<String, Session> sessionMap = new HashMap<>();

    //从服务器给某个Session发送数据 此方法名固定
    public void sendMessage(Session session,String msg) throws IOException{
        if (session!=null){
            session.getBasicRemote().sendText(msg);
        }
    }

    //用户和服务器建立连接
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "name")String userName){
        //向session集合中添加一个用户session
        sessionMap.put(userName,session);
        //在线人数+1
        addOnline();
        System.out.println(userName+"加入服务器!当前在线人数:"+online);
        try {
            //发送一段信息给登录的用户
            sendMessage(session,userName+",欢迎加入聊天室!!!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //用户退出关闭连接
    @OnClose
    public void onClose(@PathParam(value = "name")String userName){
        //移除一个Session
        sessionMap.remove(userName);
        //在线人数-1
        subOnline();
        System.out.println(userName+"断开服务器连接!当前人数:"+online);
    }
    //向所用的Session对象发送信息
    @OnMessage
    public void onMessage(String msg) throws IOException{
        for (Session session:sessionMap.values()){
            sendMessage(session,msg);
        }
    }

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

    //指定向某人发信息
    public void sendInfo(String name,String msg){
        Session session = sessionMap.get(name);
        try {
            sendMessage(session,msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //对在线人数的操作 增加
    public static void addOnline(){
        online.incrementAndGet();
    }
    //对在线人数的操作 减少
    public static void subOnline(){
        online.decrementAndGet();
    }
}

application.yml:

# 应用名称
spring:
  application:
    name: mywbsk
# 应用服务 WEB 访问端口
server:
  port: 9900

ls.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<input type="text" id="text">
<button onclick="collctive()">发送</button>
<button onclick="exitTalk()">关闭</button>
<br>
<div id="message"></div>
<script type="text/javascript">
    var webSocket = null;
    if ('WebSocket' in window){
        webSocket=new WebSocket("ws://localhost:9900/socket/ls")
    }else {
        alert("当前浏览器不支持HTML5的WebSocket!!!")
    }
    //在div中写信息的方法
    function setMsg(msg) {
        document.getElementById("message").innerHTML+=msg+"<br/>";
    }
    //前端websocket错误处理
    webSocket.onerror = function () {
        setMsg("连接服务器错误!!!");
    }
    //开启websocket服务器连接时获取后端服务器返回的数据
    webSocket.onopen = function () {
        setMsg("登录成功!!!");
    }
    //接受服务器群发或单发的数据
    webSocket.onmessage = function (event) {
        setMsg(event.data);
    }
    //用户点击按钮后接到服务器的信息
    webSocket.onclose = function () {
        setMsg("BYE BYE!!!");
    }
    //用户直接关闭浏览器
    window.onbeforeunload=function () {
        webSocket.close();
    }
    //用户发送信息到群里
    function collctive() {
        //获取文本框的值
        var msg = document.getElementById("text").value;
        //发送服务器
        webSocket.send(msg);
    }
    //用户点击按钮退出聊天室
    function exitTalk() {
        webSocket.close();
    }
</script>
</body>
</html>

zs.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<input type="text" id="text">
<button onclick="collctive()">发送</button>
<button onclick="exitTalk()">关闭</button>
<br>
<div id="message"></div>
<script type="text/javascript">
    var webSocket = null;
    if ('WebSocket' in window){
        webSocket=new WebSocket("ws://localhost:9900/socket/zs")
    }else {
        alert("当前浏览器不支持HTML5的WebSocket!!!")
    }
    //在div中写信息的方法
    function setMsg(msg) {
        document.getElementById("message").innerHTML+=msg+"<br/>";
    }
    //前端websocket错误处理
    webSocket.onerror = function () {
        setMsg("连接服务器错误!!!");
    }
    //开启websocket服务器连接时获取后端服务器返回的数据
    webSocket.onopen = function () {
        setMsg("登录成功!!!");
    }
    //接受服务器群发或单发的数据
    webSocket.onmessage = function (event) {
        setMsg(event.data);
    }
    //用户点击按钮后接到服务器的信息
    webSocket.onclose = function () {
        setMsg("BYE BYE!!!");
    }
    //用户直接关闭浏览器
    window.onbeforeunload=function () {
        webSocket.close();
    }
    //用户发送信息到群里
    function collctive() {
        //获取文本框的值
        var msg = document.getElementById("text").value;
        //发送服务器
        webSocket.send(msg);
    }
    //用户点击按钮退出聊天室
    function exitTalk() {
        webSocket.close();
    }
</script>
</body>
</html>

3.浏览器测试

群聊页面:

 

 管理员功能属于controller层,大家有兴趣的可以去试一试

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值