webscoket的前端使用
var websocket = null;
var path=window.location.href;
var projectName=path.substring(path.indexOf(window.location.host),path.indexOf("action"));
var domainName=projectName.substring(0,projectName.indexOf("/"));//获取域名
var pName=projectName.substring(projectName.indexOf("/"),projectName.lastIndexOf("/"));//获取项目名称
//判断当前浏览器是否支持WebSocket url的地址为本机ip地址+Tomcat端口号+项目名称+注解服务器端
//如果是https,需要设置域名加端口号
if ('WebSocket' in window) {
if(window.location.protocol=="http:"){
websocket = new WebSocket("ws://"+domainName+pName+"/websocket/release/mobileNotify");
}else{
websocket = new WebSocket("wss://"+domainName+pName+"/websocket/release/mobileNotify");
}
}
else {
layui.layer.msg('当前不支持websocket');
}
//连接发生错误的回调方法
websocket.onerror = function () {
console.log("连接发生错误");
};
websocket.onclose = function (e) {
console.log('websocket 断开: ' + e.code + ' ' + e.reason + ' ' + e.wasClean);
console.log(e);
}
//连接成功建立的回调方法
websocket.onopen = function () {
console.log("WebSocket连接成功");
}
//接收到消息的回调方法
websocket.onmessage = function (event) {
console.log(event.data);
var id=Date.now();
console.log(id);
Android.notice(id,event.data);//调用android端的接口发出消息提示
}
//连接关闭的回调方法
websocket.onclose = function () {
console.log("WebSocket连接关闭");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function () {
closeWebSocket();
}
//关闭WebSocket连接
function closeWebSocket() {
websocket.close();
}
//通过websocket给服务端发送消息
function send(message1) {
websocket.send(message1);
}
关键点:
使用http协议的时候使用ws://
使用https协议的时候使用wss://
地址:ws://[server]:[port]/[root]/websocket/core/notify
使用loaction中的protocol来判断使用的http还是https协议。