websocket.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@include file="/common/common-uplan.jsp"%>
<script>
var wsUri ="ws://localhost:8080/xbnet-product-web/websocket?username=${user.name}&userId=${user.operatorId}";
//判断浏览器是否支持websocket
if(window.WebSocket){
//创建websocket连接
websocket = new WebSocket(wsUri);
console.log('This browser supports WebSocket');
}else{
console.log('This browser does not supports WebSocket');
}
//连接成功建立的回调方法
websocket.onopen = function() {
writeToScreen("webSocket连接成功");
};
//连接关闭的回调方法
websocket.onclose = function() {
writeToScreen("webSocket连接关闭");
};
//接收到消息的回调方法
websocket.onmessage = function(event) {
writeToScreen(event.data);
};
//连接发生错误的回调方法
websocket.onerror = function() {
writeToScreen("WebSocket连接发生错误");
};
//关闭WebSocket连接
function closeWebSocket() {
websocket.close();
}
function doSend() {
var text = $("#text") .val();
var users = $('input:checkbox:checked');
var touser = "";
if (users.length == 0){
alert("请选择发送人!");
return;
} else{
for (var i = 0; i < users.length; i++){
touser += users[i].value + "|";
}
}
if (text != "" && text != undefined && text != null){
var obj = null;
obj = {
toUser:touser,
fromUser:"${user.operatorId}",
msg:text
};
obj = JSON.stringify(obj);
websocket.send(obj);
$("#text") .val("");
}
}
function writeToScreen(message) {
var output = document.getElementById('output');
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function () {
closeWebSocket();
}
</script>
<div id="main">
<div id="left" style="width: 350px;height: 280px;float: left;">
<!-- 消息显示栏 -->
<div id="output" style="width: 350px;height: 240px"></div><hr/>
<!-- 消息发送栏 -->
<input id="text" type="text"/>
<button onclick="doSend()">发送消息</button>
</div>
<!-- 用户列表 -->
<div class="up-form-group up-col-sm-24" style="width: 100px;height: 280px;float: right;border-left:1px solid gray">
<c:forEach items="${operator }" var="rowdata" varStatus="status">
<div class="up-col-sm-24">
<label class="u_check">
<input id="" value="${rowdata.operatorId }" type="checkbox">
<i class="up-text-primary icon-u-check-empty"></i>${rowdata.name }
</label>
</div>
</c:forEach>
</div>
</div>
<%@ page language="java" c