java前端长连接框架_Java中Spring Boot+Socket实现与html页面的长连接实例详解
Spring Boot+Socket实现与html页面的长连接,客户端给服务器端发消息,服务器给客户端轮询发送消息,附案例源码
功能介绍
客户端给所有在线用户发送消息客户端给指定在线用户发送消息服务器给客户端发送消息(轮询方式)
注意:socket只是实现一些简单的功能,具体的还需根据自身情况,代码稍微改造下
项目搭建
项目结构图
pom.xml
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.3.2.RELEASE
com.cyb
socket_test
0.0.1-SNAPSHOT
socket_test
Demo project for Spring Boot
1.8
org.springframework.boot
spring-boot-starter-websocket
com.google.guava
guava
18.0
com.alibaba
fastjson
1.2.46
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.junit.vintage
junit-vintage-engine
org.springframework.boot
spring-boot-maven-plugin
appliccation.properties
SocketTestApplication.java(Spring Boot启动类)
WebSocketStompConfig.java
package com.cyb.socket.websocket;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketStompConfig {
//这个bean的注册,用于扫描带有@ServerEndpoint的注解成为websocket ,如果你使用外置的tomcat就不需要该配置文件
@Bean
public ServerEndpointExporter serverEndpointExporter()
{
return new ServerEndpointExporter();
}
}
WebSocket.java(Socket核心类)
package com.cyb.socket.websocket;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
* @Author:陈彦斌
* @Description:Socket核心类
* @Date: 2020-07-26
*/
@Component
@ServerEndpoint(value = "/connectWebSocket/{userId}")
public class WebSocket {
private Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* 在线人数
*/
public static int onlineNumber = 0;
/**
* 以用户的姓名为key,WebSocket为对象保存起来
*/
private static Map clients = new ConcurrentHashMap();
/**
* 会话
*/
private Session session;
/**
* 用户名称
*/
private String userId;
/**
* 建立连接
*
* @param session
*/
@OnOpen
public void onOpen(@PathParam("userId") String userId, Session session) {
onlineNumber++;
System.out.println("现在来连接的客户id:" + session.getId() + "用户名:" + userId);
//logger.info("现在来连接的客户id:"+session.getId()+"用户名:"+userId);
this.userId = userId;
this.session = session;
System.out.println("有新连接加入! 当前在线人数" + onlineNumber);
// logger.info("有新连接加入! 当前在线人数" + onlineNumber);
try {
//messageType 1代表上线 2代表下线 3代表在线名单 4代表普通消息
//先给所有人发送通知,说我上线了
Map map1 = Maps.newHashMap();
map1.put("messageType", 1);
map1.put("userId", userId);
sendMessageAll(JSON.toJSONString(map1), userId);
//把自己的信息加入到map当中去
clients.put(userId, this);
System.out.println("有连接关闭! 当前在线人数" + onlineNumber);
//logger.info("有连接关闭! 当前在线人数" + clients.size());
//给自己发一条消息:告诉自己现在都有谁在线
Map map2 = Maps.newHashMap();
map2.put("messageType", 3);
//移除掉自己
Set set = clients.keySet();
map2.put("onlineUsers", set);
sendMessageTo(JSON.toJSONString(map2), userId);
} catch (IOException e) {
System.out.println(userId + "上线的时候通知所有人发生了错误");
//logger.info(userId+"上线的时候通知所有人发生了错误");
}
}
@OnError
public void onError(Session session, Throwable error) {
//logger.info("服务端发生了错误"+error.getMessage());
//error.printStackTrace();
System.out.println("服务端发生了错误:" + error.getMessage());
}
/**
* 连接关闭
*/
@OnClose
public void onClose() {
onlineNumber--;
//webSockets.remove(this);
clients.remove(userId);
try {
//messageType 1代表上线 2代表下线 3代表在线名单 4代表普通消息
Map map1 = Maps.newHashMap();
map1.put("messageType", 2);
map1.put("onlineUsers", clients.keySet());
map1.put("userId", userId);
sendMessageAll(JSON.toJSONString(map1), userId);
} catch (IOException e) {
System.out.println(userId + "下线的时候通知所有人发生了错误");
//logger.info(userId+"下线的时候通知所有人发生了错误");
}
//logger.info("有连接关闭! 当前在线人数" + onlineNumber);
//logger.info("有连接关闭! 当前在线人数" + clients.size());
System.out.println("有连接关闭! 当前在线人数" + onlineNumber);
}
/**
* 收到客户端的消息
*
* @param message 消息
* @param session 会话
*/
@OnMessage
public void onMessage(String message, Session session) {
try {
//logger.info("来自客户端消息:" + message+"客户端的id是:"+session.getId());
System.out.println("来自客户端消息:" + message + " | 客户端的id是:" + session.getId());
JSONObject jsonObject = JSON.parseObject(message);
String textMessage = jsonObject.getString("message");
String fromuserId = jsonObject.getString("userId");
String touserId = jsonObject.getString("to");
//如果不是发给所有,那么就发给某一个人
//messageType 1代表上线 2代表下线 3代表在线名单 4代表普通消息
Map map1 = Maps.newHashMap();
map1.put("messageType", 4);
map1.put("textMessage", textMessage);
map1.put("fromuserId", fromuserId);
if (touserId.equals("All")) {
map1.put("touserId", "所有人");
sendMessageAll(JSON.toJSONString(map1), fromuserId);
} else {
map1.put("touserId", touserId);
System.out.println("开始推送消息给" + touserId);
sendMessageTo(JSON.toJSONString(map1), touserId);
}
} catch (Exception e) {
e.printStackTrace();
//logger.info("发生了错误了");
}
}
/**
* 给指定的用户发送消息
*
* @param message
* @param TouserId
* @throws IOException
*/
public void sendMessageTo(String message, String TouserId) throws IOException {
for (WebSocket item : clients.values()) {
System.out.println("给指定的在线用户发送消息,在线人员名单:【" + item.userId.toString() + "】发送消息:" + message);
if (item.userId.equals(TouserId)) {
item.session.getAsyncRemote().sendText(message);
break;
}
}
}
/**
* 给所有用户发送消息
*
* @param message 数据
* @param FromuserId
* @throws IOException
*/
public void sendMessageAll(String message, String FromuserId) throws IOException {
for (WebSocket item : clients.values()) {
System.out.println("给所有在线用户发送给消息,在线人员名单:【" + item.userId.toString() + "】发送消息:" + message);
item.session.getAsyncRemote().sendText(message);
}
}
/**
* 给所有在线用户发送消息
*
* @param message 数据
* @throws IOException
*/
public void sendMessageAll(String message) throws IOException {
for (WebSocket item : clients.values()) {
System.out.println("服务器给所有在线用户发送消息,当前在线人员为【" + item.userId.toString() + "】发送消息:" + message);
item.session.getAsyncRemote().sendText(message);
}
}
/**
* 获取在线用户数
*
* @return
*/
public static synchronized int getOnlineCount() {
return onlineNumber;
}
}
TestController.java(前端控制器)
package com.cyb.socket.websocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
@Controller
@RequestMapping("testMethod")
public class TestController {
@Autowired
private WebSocket webSocket;
/**
* 给指定的在线用户发送消息
* @param userId
* @param msg
* @return
* @throws IOException
*/
@ResponseBody
@GetMapping("/sendTo")
public String sendTo(@RequestParam("userId") String userId,@RequestParam("msg") String msg) throws IOException {
webSocket.sendMessageTo(msg,userId);
return "推送成功";
}
/**
* 给所有在线用户发送消息
* @param msg
* @return
* @throws IOException
* @throws IOException
*/
@ResponseBody
@PostMapping("/sendAll")
public String sendAll(@RequestBody String msg) throws IOException, IOException {
webSocket.sendMessageAll(msg);
return "推送成功";
}
}
SocketTask.java(轮询调度往客户端推送消息)
package com.cyb.socket.schedule;
import com.cyb.socket.websocket.WebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
@Component
public class SocketTask {
@Autowired
private WebSocket webSocket;
private SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS" );
//5秒轮询一次
@Scheduled(fixedRate = 5000)
public void sendClientData() throws IOException {
String msg="{\"message\":\"你好\",\"userId\":\"002\",\"to\":\"All\"}";
webSocket.sendMessageAll(msg);
System.out.println("消息推送时间:"+ sdf.format(new Date()));
}
}
测试网页
index.html
Test My WebSocket
TestWebSocket
SEND MESSAGE
CLOSE
var websocket = null;
//判断当前浏览器是否支持WebSocket
if('WebSocket' in window){
//连接WebSocket节点
websocket = new WebSocket("ws://localhost:8083/connectWebSocket/001");
}
else{
alert('Not support websocket')
}
//连接发生错误的回调方法
websocket.onerror = function(){
setMessageInnerHTML("error");
};
//连接成功建立的回调方法
websocket.onopen = function(event){
setMessageInnerHTML("open");
}
//接收到消息的回调方法
websocket.onmessage = function(event){
setMessageInnerHTML(event.data);
}
//连接关闭的回调方法
websocket.onclose = function(){
setMessageInnerHTML("close");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function(){
websocket.close();
}
//将消息显示在网页上
function setMessageInnerHTML(innerHTML){
document.getElementById('message').innerHTML += innerHTML + '
';
}
//关闭连接
function closeWebSocket(){
websocket.close();
}
//发送消息
function send(){
var message = document.getElementById('text').value;
websocket.send(message);
}
index2.html
Test My WebSocket
TestWebSocket
SEND MESSAGE
CLOSE
var websocket = null;
//判断当前浏览器是否支持WebSocket
if('WebSocket' in window){
//连接WebSocket节点
websocket = new WebSocket("ws://localhost:8083/connectWebSocket/002");
}
else{
alert('Not support websocket')
}
//连接发生错误的回调方法
websocket.onerror = function(){
setMessageInnerHTML("error");
};
//连接成功建立的回调方法
websocket.onopen = function(event){
setMessageInnerHTML("open");
}
//接收到消息的回调方法
websocket.onmessage = function(event){
setMessageInnerHTML(event.data);
}
//连接关闭的回调方法
websocket.onclose = function(){
setMessageInnerHTML("close");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function(){
websocket.close();
}
//将消息显示在网页上
function setMessageInnerHTML(innerHTML){
document.getElementById('message').innerHTML += innerHTML + '
';
}
//关闭连接
function closeWebSocket(){
websocket.close();
}
//发送消息
function send(){
var message = document.getElementById('text').value;
websocket.send(message);
}
项目地址
链接:https://pan.baidu.com/s/1yiAXTkCjHac-F3S1HFyNJQ提取码:53tp
功能演示
客户端给所有在线用户发消息
客户端给指定在线用户发送消息
服务器给客户端发送消息(轮询方式)
注意需要加上这些注解
演示
通过前端控制器给指定用户发送消息
演示
到此这篇关于Java中Spring Boot+Socket实现与html页面的长连接实例详解的文章就介绍到这了,更多相关Java Spring Boot+Socket实现与html页面的长连接内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
java前端长连接框架_Java中Spring Boot+Socket实现与html页面的长连接实例详解相关推荐
- Spring Boot 2.x的默认日志管理与Logback配置详解
前沿技术早知道,弯道超车有希望 积累超车资本,从关注DD开始 Spring Boot在所有内部日志中使用Commons Logging,但是对底层日志的实现是开放的.在Spring Boot生态中,为 ...
- Spring Boot使用hikari、druid、c3p0等数据库连接池详解
文章目录 前言 Hikari连接池 Druid连接池 Druid(新版starter)连接池 C3P0连接池(1 C3P0连接池(2 扩展 前言 截至Spring Boot V2.0为止,官方仅为下列 ...
- java发邮件的框架_Java的Spring框架中实现发送邮件功能的核心代码示例
Spring中已经封装了邮件操作类,通过spring配置文件可以便捷地注入到controller.action等地方. 下面是配置: p:host="${mail.host}" p ...
- java 获得当月天数_java中 如何获取当月的天数、指定日期的月份天数详解
代码实现如下:import java.util.Calendar; public class GetDay { public static void main(String[] args) { int ...
- spring boot 源码_SpringBoot2.1.x源码环境搭建详解
前言 笔者试着从GitHub上拉取SpringBoot源码.然鹅,在本地IDEA打开后,爆各种编译错误,各种问题.经过反复操作,现在总结一下SpringBoot源码环境搭建的实践,便于后期对于源码的学 ...
- python中代理模式分为几种_Python设计模式之代理模式实例详解
本文实例讲述了Python设计模式之代理模式.分享给大家供大家参考,具体如下: 代理模式(Proxy Pattern):为其他对象提供一种代理以控制对这个对象的访问 #!/usr/bin/env py ...
- c语言二级指针有什么作用,C语言中二级指针的实例详解
C语言中二级指针的实例详解 C语言中二级指针的实例详解 用图说明 示例代码: #include int main(int argc, const char * argv[]) { // int a = ...
- java中将json字符串_Java中JSON字符串与java对象的互换实例详解
在开发过程中,经常需要和别的系统交换数据,数据交换的格式有XML.JSON等,JSON作为一个轻量级的数据格式比xml效率要高,XML需要很多的标签,这无疑占据了网络流量,JSON在这方面则做的很好, ...
- java中匿名内部类详解_java 中匿名内部类的实例详解
搜索热词 java 中匿名内部类的实例详解 原来的面貌: class TT extends Test{ void show() { System.out.println(s+"~~~哈哈&q ...
最新文章
- PostgreSQL 数据目录结构
- python语法基础整理_Python基础
- 网络中的计算机如果加入家庭组,win10系统加入其他计算机家庭组的操作方法
- Python调用Java代码部署及初步使用
- Java-构建器模式(Buider模式)
- 强化学习 马尔可夫决策过程(MDP)是什么
- 《apue》 首次拜读完经典之作,两三记录
- win10没有realtek高清晰音频管理器_【微软】第49期分享:装完Win 10最新补丁数据没了!...
- PHP(阿里云短信验证码)
- 锐捷破号破解流程笔记
- wav怎么转换成mp3?
- 配置Ubuntu软件源
- 视频编码中CBR和VBR的区别,CRF和CQP的区别
- android系统应用程序电量消耗计算方法
- 【UE】Slate编辑器动态添加Button
- 深度学习主机环境配置: Ubuntu16.04+Nvidia GTX 1080/980ti+CUDA8.0
- Adobe Illustrator(AI)中输入希腊字母等特殊字符
- 拨号宽带服务器无响应是什么意思,宽带拨号服务器无响应
- 详解servlet生命周期
- 如何进行网站性能优化?
热门文章
- 九个很有用的 PHP 代码
- JS逆向--PyExecJS基本用法--网易云音乐逆向思路,node.js安装教程,逆向思路,逆向分析,加密机制,RSA,AES加密算法,加密算法啊破解,js引擎,定位数据包,分析栈结构,无痕窗口
- pythontk中text设滚动条_Tkinter中的滚动条在文本widg中
- 杰理之双mICENC 测试主MIC【篇】
- ShaderJoy —— 三种 USM 锐化算法和实现 【GLSL】
- MATLAB特征值的计算之eig()函数存在的问题
- MATLAB中eig的作用
- 小学信息技术用计算机画画教案,小学信息技术第4节用电脑画画4课时教案.doc
- 理解kaggle比赛大杀器xgboost
- Kaldi-dnn 学习01