效果如下:

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>

springboot+websocket实现简单的在线聊天功能的更多相关文章

  1. 基于PHP实现一个简单的在线聊天功能(轮询ajax )

    基于PHP实现一个简单的在线聊天功能(轮询ajax ) 一.总结 1.用的轮询ajax 二.基于PHP实现一个简单的在线聊天功能 一直很想试着做一做这个有意思的功能,感觉复杂的不是数据交互和表结构,麻 ...

  2. JAVA结合WebSocket实现简单客服聊天功能

    说明:该示例只简单的实现了客服聊天功能. 1.聊天记录没有保存到数据库中,一旦服务重启,消息记录将会没有,如果需要保存到数据库中,可以扩展 2.页面样式用的网上模板,样式可以自己进行修改 3.只能由用 ...

  3. 使用WebSocket实现简单的在线聊天室

    前言:我自已在网上找好了好多 WebSocket 制作 在线聊天室的案列,发现大佬们写得太高深了 我这种新手看不懂,所以就自已尝试写了一个在线简易聊天室 (我只用了js 可以用jq ) 话不多说,直接 ...

  4. WebSocket实现简单的在线聊天

    SuperWebSocket在WebService中的应用 最开始使用是寄托在IIS中,发布之后测试时半个小时就会断开,所以改为WindowsService 1. 新建Windows服务项目[Test ...

  5. 使用websocket实现在线聊天功能

    很早以前为了快速达到效果,使用轮询实现了在线聊天功能,后来无意接触了socket,关于socket我的理解是进程间通信,首先要有服务器跟客户端,服务的启动监听某ip端口定位该进程,客户端开启socke ...

  6. 基于Server-Sent Event的简单聊天室 Web 2.0时代,即时通信已经成为必不可少的网站功能,那实现Web即时通信的机制有哪些呢?在这门项目课中我们将一一介绍。最后我们将会实现一个基于Server-Sent Event和Flask简单的在线聊天室。

    基于Server-Sent Event的简单聊天室 Web 2.0时代,即时通信已经成为必不可少的网站功能,那实现Web即时通信的机制有哪些呢?在这门项目课中我们将一一介绍.最后我们将会实现一个基于S ...

  7. Spring Websocket实现简易在线聊天功能

    针对Spring Websocket的实现,我参照了其他博主的文章https://www.cnblogs.com/leechenxiang/p/5306372.html 下面直接给出实现: 一.引入相 ...

  8. websocket简单实现在线聊天

    WebSocket简介与消息推送 B/S架构的系统多使用HTTP协议,HTTP协议的特点: 1 无状态协议2 用于通过 Internet 发送请求消息和响应消息3 使用端口接收和发送消息,默认为80端 ...

  9. html5+springboot+websocket的简单实现

    环境 window7,IntelliJ IDEA 2019.2 x64 背景:利用IntelliJ来搭建springboot框架,之后来实现websocket的功能.websocket只是实现了画面上 ...

随机推荐

  1. 完美解决方案-雪花算法ID到前端之后精度丢失问题

    最近公司的一个项目组要把以前的单体应用进行为服务拆分,表的ID主键使用Mybatis plus默认 的雪花算法来生成. 快下班的时候,小伙伴跑过来找我,:"快给我看看这问题,卡这卡了小半天了 ...

  2. python3.6和pip3:Ubuntu下安装升级与踩坑之路

    本文以Ubuntu16.x系统为例,演示如何安装python3.6和相应环境.安装Python3的机器必须要能访问外网才能进行如下操作! 1. 安装方式 在Ubuntu下安装python有两种方式: ...

  3. Spring_mybatis结合之1.1

    Spring和mybatis结合,Spring管理容器,连接数据库等,mybatis负责管理sql语句,sql的入参和出参等 三种方法: 1.原始dao开发(不怎么用,好奇的宝宝可以自己搜搜.是dao ...

  4. Chrome开发者工具调试详解

    chrome开发者工具最常用的四个功能模块:元素(ELements).控制台(Console).源代码(Sources),网络(Network). 元素(Elements):用于查看或修改HTML元素 ...

  5. Java 获取一段时间内的每一天

    有时候我们会遇到一些业务场景,需要去获取一段时间内的每一天日期 public static List<Date> findDates(Date dBegin, Date dEnd) { L ...

  6. Shader Graph

    About Shader Graph https://docs.unity3d.com/Packages/com.unity.shadergraph@7.3/manual/index.html uni ...

  7. 关于babel你需要知道的事情

    babel js转码器 ES6 ==> ES5 配置 .babelrc

  8. BasicInterpreter2 改进版,简化了print函数

    源码:https://files.cnblogs.com/files/heyang78/BasicInterpreter2-20200601-3.rar 改进后使得变量和字符串可以一起输出了. 输入脚 ...

  9. Agumaster页面样式就绪

  10. Oracle 根据不同成绩,对应不同等级信息

    --查询每一颗成绩的:优秀.良好.不良的数量 --校园需要一张各科成绩状态统计表,格式如下: --科目名称 优秀人数 良好人数 不良人数 --高等数学 5 12 2 --英语 8 18 1 先创建一个 ...