springboot+websocket实现简单的在线聊天功能
效果如下:

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实现简单的在线聊天功能的更多相关文章
- 基于PHP实现一个简单的在线聊天功能(轮询ajax )
基于PHP实现一个简单的在线聊天功能(轮询ajax ) 一.总结 1.用的轮询ajax 二.基于PHP实现一个简单的在线聊天功能 一直很想试着做一做这个有意思的功能,感觉复杂的不是数据交互和表结构,麻 ...
- JAVA结合WebSocket实现简单客服聊天功能
说明:该示例只简单的实现了客服聊天功能. 1.聊天记录没有保存到数据库中,一旦服务重启,消息记录将会没有,如果需要保存到数据库中,可以扩展 2.页面样式用的网上模板,样式可以自己进行修改 3.只能由用 ...
- 使用WebSocket实现简单的在线聊天室
前言:我自已在网上找好了好多 WebSocket 制作 在线聊天室的案列,发现大佬们写得太高深了 我这种新手看不懂,所以就自已尝试写了一个在线简易聊天室 (我只用了js 可以用jq ) 话不多说,直接 ...
- WebSocket实现简单的在线聊天
SuperWebSocket在WebService中的应用 最开始使用是寄托在IIS中,发布之后测试时半个小时就会断开,所以改为WindowsService 1. 新建Windows服务项目[Test ...
- 使用websocket实现在线聊天功能
很早以前为了快速达到效果,使用轮询实现了在线聊天功能,后来无意接触了socket,关于socket我的理解是进程间通信,首先要有服务器跟客户端,服务的启动监听某ip端口定位该进程,客户端开启socke ...
- 基于Server-Sent Event的简单聊天室 Web 2.0时代,即时通信已经成为必不可少的网站功能,那实现Web即时通信的机制有哪些呢?在这门项目课中我们将一一介绍。最后我们将会实现一个基于Server-Sent Event和Flask简单的在线聊天室。
基于Server-Sent Event的简单聊天室 Web 2.0时代,即时通信已经成为必不可少的网站功能,那实现Web即时通信的机制有哪些呢?在这门项目课中我们将一一介绍.最后我们将会实现一个基于S ...
- Spring Websocket实现简易在线聊天功能
针对Spring Websocket的实现,我参照了其他博主的文章https://www.cnblogs.com/leechenxiang/p/5306372.html 下面直接给出实现: 一.引入相 ...
- websocket简单实现在线聊天
WebSocket简介与消息推送 B/S架构的系统多使用HTTP协议,HTTP协议的特点: 1 无状态协议2 用于通过 Internet 发送请求消息和响应消息3 使用端口接收和发送消息,默认为80端 ...
- html5+springboot+websocket的简单实现
环境 window7,IntelliJ IDEA 2019.2 x64 背景:利用IntelliJ来搭建springboot框架,之后来实现websocket的功能.websocket只是实现了画面上 ...
随机推荐
- 迷上我成真恋爱学心理学挽回她PDF文档资料完整版情感技巧脱单教程
迷上我成真恋爱学心理学挽回她PDF文档资料完整版情感技巧脱单教程 成真迷上我偷听女人心挽回她课程 百度网盘迷上我教程pdf地址 百度网盘挽回她教程pdf+视频的地址 备用地址淘宝百度网盘发货地址 百度 ...
- 从零搭建Spring Boot脚手架(7):整合OSS作为文件服务器
1. 前言 文件服务器是一个应用必要的组件之一.最早我搞过FTP,然后又用过FastDFS,接私活的时候我用MongoDB也凑合凑合.现如今时代不同了,开始流行起了OSS. Gitee: https: ...
- 更改默认Xcode
更改默认 Xcode 的指令: sudo xcode-select -switch /Applications/Xcode.app 如果系统里面有好几个版本的 Xcode,可以用这个命令指定默认的 ...
- 2020重新出发,MySql基础,MySql视图&索引&存储过程&触发器
@ 目录 视图是什么 视图的优点 1) 定制用户数据,聚焦特定的数据 2) 简化数据操作 3) 提高数据的安全性 4) 共享所需数据 5) 更改数据格式 6) 重用 SQL 语句 MySQL创建视图 ...
- 我是怎样刚拿饿了么P7 offer,然后途虎一轮游的
今年初拿了个饿了么P7的offer,于此同时大家顺便看看我怎么途虎一轮游的.废话不多说,直接上题吧. 一面 首先上来就是自我介绍,简单的说下自己的项目经验,涉及的技术栈之类的. 然后每一轮必问的问题来 ...
- 【代码优化】Unity查漏补缺
1.XML: 使用Unity社区中的开源脚本(Js语言)解析XML文件,网址:http://dev.grumpyferret.com/unity/,已打包XMLParser.unitypackage, ...
- HDU多校1003-Divide the Stones(构造)
Problem Description There are n stones numbered from 1 to n.The weight of the i-th stone is i kilogr ...
- Codeforces1365
AC代码 A. Matrix Game 对于给定矩阵,剩余可用的位置的数目是确定的,根据奇偶性判断就完事了. B. Trouble Sort 如果数组\(b\)有0有1,那么Yes.否则只有数组\(a ...
- chrome设置跨域访问
1.新建目录 /usr/local/opt/myChromData 2.输入命令行 open -n /Applications/Google\ Chrome.app/ --args --disable ...
- 使用Flashback救回被误drop掉的表
如果不慎把表drop掉了,并非一定要跑路,也许下面的文字能打救你. 比如现在有个testtb表,里面有一百万数据: SQL> select count(*) from testtb; COUNT ...