Spring Boot整合websocket实现点对点聊天,离线接收消息
之前一直想在项目里实现一个聊天的功能,这次终于抽空做了个点对点以及离线接收消息的功能。后面有时间再进行一些细节的完善。先mark一下。
- 前端页面设置
- js控制前端传送数据到后台,接收后台传来的数据
- java实现后台控制
一、页面设置
css的样式不多,我直接写在html了
我的用户名是登录显示,获取session里的值,对象用户是从上一个后台传过来的。
如果是想测试功能,可以在页面给对象用户一个值,也可以利用获取后台已登录的用户,显示在页面,对其进行选择
可以利用select–option标签实现选择某个用户名,设置对象用户值,我利用的是ul和li是为了页面好看一些,还没完善点击某个用户名,代表选择与其进行对话
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>websocket</title>
<link rel="stylesheet" type="text/css" href="http://localhost:8080/static/css/common.css">
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.min.js"></script>
<script src="http://cdn.bootcss.com/stomp.js/2.3.3/stomp.min.js"></script>
<style type="text/css">
#message{
margin: auto;
text-align: center;
width: 700px;
}
.setLi{
background-color: #ecafaf;
opacity: 0.4;
list-style: none;
line-height: 60px;
height: 60px;
}
#onLineUser{
margin-top: 25px;
padding: 0px;
color: #2230d8;
text-align: center;
font-size: large;
}
.divFlow{
overflow-x: auto;
overflow-y: auto;
height: 610px;
width:750px;
border:1px solid black"
}
</style>
</head>
<body>
<div style="margin: auto;text-align: center">
<h1>Welcome to websocket</h1>
</div>
<br/>
<div class="container">
<div class="row">
<!-- 左边 -->
<div class="setGrey col-sm-3" style="height:700px">
<ul id="onLineUser">
<li class="setLi" id="all">--所有--</li><hr/>
</ul>
</div>
<!-- 右边 -->
<div class="col-sm-8">
<input id="text" type="text" />
<button onclick="send()">发送消息</button>
<button onclick="closeWebSocket()">关闭连接</button>
<hr/>
<div id="userInfo"></div>
<div class="divFlow" style="border: 1px solid black">
<table id="message"></table>
</div>
<input type="text" id="userTo" th:value="${userTo}" hidden="hidden"/>
</div>