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只是实现了画面上 ...
随机推荐
- PHP学习中的一些总结(持续更新)
文件上传部分 在前台的<form>表单中 hidden隐藏域的MAX_FILE_SIZE可以起到实质性的控制作用,即在文件上传之前就可以判断文件的大小,格式为: <form acti ...
- Vue + axios + SpringBoot 2实现导出Excel
Vue + axios + SpringBoot 2实现导出Excel 1. 前端js代码-发送Http请求 /** * 文件下载 * @param url 下载地址 * @param fileNam ...
- 为何要做seo关键词排名
http://www.wocaoseo.com/thread-229-1-1.html 武汉seo百度指数在150左右,做seo的同仁们都知道这样的一件事情. 真正搜索武汉seo关键词能作为潜在客户的 ...
- .Net 单元测试框架xUnit使用
使用前需要导入下面的NuGet包:(不然可能会导致测试代码无法运行) .net版本 .net core3.1 Moq这个包只有需要Mock的时候才需要导入(不清楚Mock的话可以留言或自行百度) 开始 ...
- Android开发之将图片文件转化为字节数组字符串,并对其进行Base64编码处理
作者:程序员小冰,CSDN博客:http://blog.csdn.net/qq_21376985, 转载请说明出处. /** * @将图片文件转化为字节数组字符串,并对其进行Base64编码处理 * ...
- PageObject六大原则
The public methods represent the services that the page offers 公共方法表示页面提供的服务 Try not to expose the i ...
- SpringCloud系列之Nacos+Dubbo应用篇
目录 前言 项目版本 项目说明 项目结构 集成Dubbo2.6.x 支付模块 用户模块 集成Dubbo2.7.x 支付模块 用户模块 测试验证 参考资料 系列文章 前言 本文在前篇文章<Spri ...
- Palindrome subsequence(区间dp+容斥)
In mathematics, a subsequence is a sequence that can be derived from another sequence by deleting so ...
- java初探(1)之秒杀的安全
在秒杀的场景中还存在着很多的安全问题 暴露秒杀地址 秒杀请求可以很频繁 接口流量大,恶意刷接口 隐藏秒杀接口 为什么需要隐藏,事实上,页面上的所有东西都能被客户端拿到,包括js代码,因此,分析商品详情 ...
- 深入了解Kafka【五】Partition和消费者的关系
1.消费者与Partition 以下来自<kafak权威指南>第4章. 假设主题T1有四个分区. 1.1.一个消费者组 1.1.1.消费者数量小于分区数量 只有一个消费者时,消费者1将收到 ...