微服务-springboot+websocket在线聊天室
一.引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
二.注入ServerEndpointExporter
编写一个WebSocketConfig配置类,注入对象ServerEndpointExporter,
这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter; /**
* @Description: 编写一个WebSocketConfig配置类,注入对象ServerEndpointExporter,
* 这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
*/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
三.websocket的具体实现类
使用springboot的唯一区别是要@Component声明下,而使用独立容器是由容器自己管理websocket的,
但在springboot中连容器都是spring管理的。
虽然@Component默认是单例模式的,但springboot还是会为每个websocket连接初始化一个bean,
所以可以用一个静态set保存起来。
import org.springframework.stereotype.Component; import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.CopyOnWriteArraySet; /**
* * @Description: websocket的具体实现类
* * 使用springboot的唯一区别是要@Component声明下,而使用独立容器是由容器自己管理websocket的,
* * 但在springboot中连容器都是spring管理的。
* 虽然@Component默认是单例模式的,但springboot还是会为每个websocket连接初始化一个bean,
* 所以可以用一个静态set保存起来。
*/
@ServerEndpoint(value = "/websocket")
@Component
public class MyWebSocket {
//用来存放每个客户端对应的MyWebSocket对象。
private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>(); //与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session; /**
* 连接建立成功调用的方法
*/
@OnOpen
public void onOpen(Session session) {
this.session = session;
webSocketSet.add(this); //加入set中
System.out.println("有新连接加入!当前在线人数为" + webSocketSet.size());
//群发消息,告诉每一位
broadcast(session.getId()+"连接上WebSocket-->当前在线人数为:"+webSocketSet.size());
} /**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //从set中删除
System.out.println("有一连接关闭!当前在线人数为" + webSocketSet.size()); //群发消息,告诉每一位
broadcast(session.getId()+"下线,当前在线人数为:"+webSocketSet.size());
} /**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
* */
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("来自客户端的消息:" + message);
//群发消息
broadcast(message);
} /**
* 发生错误时调用
*
*/
@OnError
public void onError(Session session, Throwable error) {
System.out.println("发生错误");
error.printStackTrace();
} /**
* 群发自定义消息
* */
public void broadcast(String message){
for (MyWebSocket item : webSocketSet) {
//同步异步说明参考:http://blog.csdn.net/who_is_xiaoming/article/details/53287691
//this.session.getBasicRemote().sendText(message);
item.session.getAsyncRemote().sendText(message);//异步发送消息.
}
}
}
四.编写index.ftl
<!DOCTYPE html>
<html>
<head lang="en">
<title>Spring Boot Demo - FreeMarker</title> <link href="/css/index.css" rel="stylesheet" />
<script src="/js/index.js"></script>
</head>
<body>
<button onclick="connectWebSocket()">连接WebSocket</button>
<button onclick="closeWebSocket()">断开连接</button>
<hr />
<br />
消息:<input id="text" type="text" />
<button onclick="send()">发送消息</button>
<div id="message"></div>
</body>
</html>
五.编写index.js
var websocket = null;
function connectWebSocket(){
//判断当前浏览器是否支持WebSocket
//判断当前浏览器是否支持WebSocket
if ('WebSocket'in window) {
websocket = new WebSocket("ws://localhost:8080/websocket");
} else {
alert('当前浏览器不支持websocket');
} //连接发生错误的回调方法
websocket.onerror = function() {
setMessageInnerHTML("error");
}; //接收到消息的回调方法
websocket.onmessage = function(event) {
setMessageInnerHTML(event.data);
} //连接关闭的回调方法
websocket.onclose = function() {
setMessageInnerHTML("Loc MSG:关闭连接");
} //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function() {
websocket.close();
}
} //将消息显示在网页上
function setMessageInnerHTML(innerHTML) {
document.getElementById('message').innerHTML += innerHTML + '<br/>';
} //关闭连接
function closeWebSocket() {
websocket.close();
} //发送消息
function send() {
var message = document.getElementById('text').value;
websocket.send(message);
}
六.index.css
#message{
margin-top:40px;
border:1px solid gray;
padding:20px;
}
七.controller
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; @Controller
@RequestMapping("web")
public class WebController { @RequestMapping("index")
public String index(){
return "index";
}
}
测试:http://localhost:8080/web/index
点击【连接WebSocket】,然后就可以发送消息了。

打开另外一个浏览器或者直接打开一个TAB访问地址http://localhost:8080/web/index
点击【连接WebSocket】,然后就可以发送消息了。
观察两边的信息打印,看是否可以接收到消息。
源码:下载地址
单聊
一.创建消息对象socketMsg
public class SocketMsg {
private int type;//聊天类型0:群聊,1:单聊
private String fromuUser://发送者
private String toUser;//接收者
private String msg;//发送的消息
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getFromuUser() {
return fromuUser;
}
public void setFromuUser(String fromuUser) {
this.fromuUser = fromuUser;
}
public String getToUser() {
return toUser;
}
public void setToUser(String toUser) {
this.toUser = toUser;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
二.调整建立连接的方法(MyWebSocket):
这里主要是要使用一个map对象保存频道号和session之前的关系,之后就可以通过频道号获取session,然后使用session进行消息的发送。
//用来记录sessionId和该session进行绑定
private static ConcurrentHashMap<String,Session> map = new ConcurrentHashMap<String, Session>();
三.修改连接的方法onOpen:
在建立连接的时候,就保存频道号(这里使用的是session.getId()作为频道号)
/**
* 连接建立成功调用的方法
*/
@OnOpen
public void onOpen(Session session) {
this.session = session;
map.put(session.getId(),session); webSocketSet.add(this); //加入set中
System.out.println("有新连接加入:"+session.getId()+"!当前在线人数为" + webSocketSet.size());
//群发消息,告诉每一位
broadcast(session.getId()+"连接上WebSocket-->当前在线人数为:"+webSocketSet.size());
}
三.修改消息发送的方法onMessage:
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
* */
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("来自客户端的消息:" + session.getId() + ":" + message); //从客户端传过来的数据是json数据,所以这里使用jackson进行转换为SocketMsg对象,
// 然后通过socketMsg的type进行判断是单聊还是群聊,进行相应的处理:
ObjectMapper objectMapper = new ObjectMapper();
SocketMsg socketMsg;
try {
socketMsg = objectMapper.readValue(message, SocketMsg.class);
if(socketMsg.getType() == 1){
//单聊
socketMsg.setFromUser(session.getId());//发送者.
Session fromSession = map.get(socketMsg.getFromUser());
Session toSession = map.get(socketMsg.getToUser());
if(toSession != null){
//发送给发送者和接受者.
fromSession.getAsyncRemote().sendText(session.getId()+":"+socketMsg.getMsg());
toSession.getAsyncRemote().sendText(session.getId()+":"+socketMsg.getMsg());
}else{
//发送给发送者
fromSession.getAsyncRemote().sendText("系统消息:对方已下线");
}
}else{
//群聊
broadcast(message);
}
} catch (IOException e) {
e.printStackTrace();
}
}
四.页面调整
消息:<input id="text" type="text" />
接收者:<input id="toUser" type="text" />
<button onclick="send()">发送消息</button>
五.js调整
//发送消息
function send() {
var message = document.getElementById('text').value;
var toUser = document.getElementById('toUser').value;
var socketMsg = {msg:message,toUser:toUser};
if(toUser == ''){
//群聊.
socketMsg.type = 0;
}else{
//单聊.
socketMsg.type = 1;
}
websocket.send(JSON.stringify(message));
}
运行测试:
2的消息:

1的消息:

0的消息:

源码:下载地址
微服务-springboot+websocket在线聊天室的更多相关文章
- 基于WebSocket和SpringBoot的群聊天室
引入 普通请求-响应方式:例如Servlet中HttpServletRequest和HttpServletResponse相互配合先接受请求.解析数据,再发出响应,处理完成后连接便断开了,没有数据的实 ...
- 在线聊天室的实现(1)--websocket协议和javascript版的api
前言: 大家刚学socket编程的时候, 往往以聊天室作为学习DEMO, 实现简单且上手容易. 该Demo被不同语言实现和演绎, 网上相关资料亦不胜枚举. 以至于很多技术书籍在讲解网络相关的编程时, ...
- 使用WebSocket实现简单的在线聊天室
前言:我自已在网上找好了好多 WebSocket 制作 在线聊天室的案列,发现大佬们写得太高深了 我这种新手看不懂,所以就自已尝试写了一个在线简易聊天室 (我只用了js 可以用jq ) 话不多说,直接 ...
- 基于Server-Sent Event的简单在线聊天室
Web即时通信 所谓Web即时通信,就是说我们可以通过一种机制在网页上立即通知用户一件事情的发生,是不需要用户刷新网页的.Web即时通信的用途有很多,比如实时聊天,即时推送等.如当我们在登陆浏览知乎时 ...
- 基于WebSocket实现聊天室(Node)
基于WebSocket实现聊天室(Node) WebSocket是基于TCP的长连接通信协议,服务端可以主动向前端传递数据,相比比AJAX轮询服务器,WebSocket采用监听的方式,减轻了服务器压力 ...
- Ext JS学习第十六天 事件机制event(一) DotNet进阶系列(持续更新) 第一节:.Net版基于WebSocket的聊天室样例 第十五节:深入理解async和await的作用及各种适用场景和用法 第十五节:深入理解async和await的作用及各种适用场景和用法 前端自动化准备和详细配置(NVM、NPM/CNPM、NodeJs、NRM、WebPack、Gulp/Grunt、G
code&monkey Ext JS学习第十六天 事件机制event(一) 此文用来记录学习笔记: 休息了好几天,从今天开始继续保持更新,鞭策自己学习 今天我们来说一说什么是事件,对于事件 ...
- JAVA实现webSocket网页聊天室
一.什么是webSocket WebSocket 是一种网络通信协议,是持久化协议.RFC6455 定义了它的通信标准. WebSocket 是 HTML5 开始提供的一种在单个 TCP 连接上进行全 ...
- swoole中websoket创建在线聊天室(php)
swoole中websoket创建在线聊天室(php) swoole现仅支持Linix,macos 创建websocket服务器 首先现在服务器创建一个websocket服务器 <?php // ...
- 基于JQuery+JSP的无数据库无刷新多人在线聊天室
JQuery是一款非常强大的javascript插件,本文就针对Ajax前台和JSP后台来实现一个无刷新的多人在线聊天室,该实现的数据全部存储在服务端内存里,没有用到数据库,本文会提供所有源程序,需要 ...
随机推荐
- 记一次删除Git记录中的大文件的过程
app/test/target/ #查看大文件 git rev-list --objects --all | grep "$(git verify-pack -v .git/objects/ ...
- 二叉树C语言
几乎报价http://blog.csdn.net/hopeyouknow/article/details/6740616.为了这细微的地方进行了修改.他能够执行. bitree.h typedef i ...
- 你好,Oh My Zsh - 社区力量全新方式定义命令行 | 咖啡时间
Oh My Zsh 是一款社区驱动的命令行工具,正如它的主页上说的,Oh My Zsh 是一种生活方式.它基于 zsh 命令行,提供了主题配置,插件机制,已经内置的便捷操作.给我们一种全新的方式使用命 ...
- JDK源码阅读——Vector实现
1 继承结构图 Vector同样继承自AbstractList,与ArrayList.LinedList一样,是List的一种实现 2 数据结构 // 与ArrayList一样,也是使用对象数组保存元 ...
- 芯片超Intel,盈利比肩Apple,三星成科技界"全民公敌"
原标题:芯片超英特尔,盈利比肩苹果:三星现在是科技界“全民公敌”了 当人们津津乐道于三星的手机业务或者是电视业务时,它已静悄悄的拿下了芯片行业的第一,并且凭借着在芯片上的巨大获利让它的老对手们眼红 ...
- SQL Server 阻止组件 xp_cmdshell
错误信息描述 消息 15281,级别 16,状态 1,过程 xp_cmdshell,第 1 行SQL Server 阻止了对组件 'xp_cmdshell' 的 过程 'sys.xp_cmdshell ...
- ELINK编程器典型场景之多APP文件下载
有些应用场合中,单MCU内会采用BootLoader+APP1+APP2的加载模式,程序启动时先进入BootLoader程序,依据设定条件跳转至APPx应用运行:为满足此类需求,设计多达5个程序文件( ...
- linux下计划任务学习记录
0x01 计划任务简介 linux 中计划任务主要分为”循环执行”和”只执行一次”两种,分别对应的时 crond 服务 和 atd 服务: 0x02 只执行一次的计划任务 0x02.1 atd 服务说 ...
- RxJava入门优秀博客推荐
RxJava用了快半年了,现在越来越离不开这个库,从使用到逐渐接触它的背后实现,突然想写点什么关于RxJava的内容.在酝酿如何组织内容的时候,就去看看自己关于RxJava的收藏,发现满满的干货! 1 ...
- 【JDK源码分析】String的存储区与不可变 专题
<Think in Java>中说:“关系操作符生成的是一个boolean结果,它们计算的是操作数的值之间的关系”. "=="判断的是两个对象的内存地址是否一样,适用于 ...