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只是实现了画面上 ...
随机推荐
- IDEA下Maven项目搭建踩坑记----3.最长的bug,最简单的错误。同一类中,部分函数的@AutoWired注入的对象失效
这个错误绝对是我写到现在为止最傻X的一个错误,先上图 问题: 出了一个特别长的错误,大致的意思就是mapper.xml文件注入Dao层的时候失败. 解决: 查看一下错误的位置→ 找到Dao层 找到错误 ...
- C语言基础练习——打印菱形
C语言基础练习--打印菱形 JERRY_Z. ~ 2020 / 8 / 26 转载请注明出处! 代码: /* * @Author: JERRY_Z. * @Date: 2020-08-26 17:17 ...
- CSS 段落/换行/缩进
CSS 段落/换行/缩进 1.盒模型 box-sizing: content-box|border-box|inherit; content-box(默认) : 实际宽度/高度 = width/hei ...
- Java后台服务慢优化杂谈
Java后台服务慢优化杂谈 前言 你是否遇到过这样的场景,当我们点击页面某个按钮后,页面一直loading,要等待好几分钟才出结果的画面,有时直接502或504,作为一个后台开发,看到自己开发的系统是 ...
- py_创建文件以及写入读取数据+异常处理
import readline import math import json ''' A: 第一行 第二行 第三行 ''' #从文件读取数据 with open("D:\A.txt&quo ...
- Promise对象入门
简介 promise对象可以获取异步操作的消息,提供统一的API,各个异步操作都可以用同样的方法进行处理. promise对象不受外界影响,其有三种状态:pending(进行中).fulfilled( ...
- 由浅入深理解 IOC 和 DI
目录 由浅入深理解 IOC 和 DI 开闭原则 OCP(Open Closed Principle) 面向抽象编程 逐步理解实现 IOC 和 DI 的过程(LOL Demo 示例) 比较尴尬的编写程序 ...
- MSP430-LED中断闪烁代码详解
使用MSP430F149的开发板,首先对LED闪烁灯的例程进行讲解,然后下边是自己写的,将部分代码写入了新建的led.c程序中 #include <msp430x14x.h> ...
- 几个Graphics函数
1.Graphics.Blit:Copies source texture into destination render texture with a shader 声明: 1.public sta ...
- Maxscript中渲染中文版Vray完成贴图(VrayCompleteMap)的方法
Objbakeproperties = $.INodeBakeProperties; --选定对象的烘培节点 Prjbakeproperties = $.INodeBakeProjProperties ...