java网页消息推送实例_java WebSocket 简易聊天消息推送实例方法介绍

String path = request.getContextPath();

String basePath = request.getScheme()+”://”+request.getServerName()+”:”+request.getServerPort()+path+”/”;

%>

测试

input#chat {

width: 410px

}

#console-container {

width: 400px;

}

#console {

border: 1px solid #CCCCCC;

border-right-color: #999999;

border-bottom-color: #999999;

height: 170px;

overflow-y: scroll;

padding: 5px;

width: 100%;

}

#console p {

padding: 0;

margin: 0;

}

var Chat = {};

Chat.socket = null;

Chat.connect = (function(host) {

if (‘WebSocket’ in window) {

Chat.socket = new WebSocket(host);

} else if (‘MozWebSocket’ in window) {

Chat.socket = new MozWebSocket(host);

} else {

Console.log(‘Error: WebSocket is not supported by this browser.’);

return;

}

Chat.socket.onopen = function () {

Console.log(‘Info: WebSocket connection opened.’);

document.getElementById(‘chat’).onkeydown = function(event) {

if (event.keyCode == 13) {

Chat.sendMessage();

}

};

};

Chat.socket.onclose = function () {

document.getElementById(‘chat’).onkeydown = null;

Console.log(‘Info: WebSocket closed.’);

};

Chat.socket.onmessage = function (message) {

Console.log(message.data);

};

});

Chat.initialize = function() {

if (window.location.protocol == ’http:’) {

Chat.connect(‘ws://’ + window.location.host + ’/socket2/websocket/chat’);

} else {

Chat.connect(‘wss://’ + window.location.host + ’/socket2/websocket/chat’);

}

};

Chat.sendMessage = (function() {

var message = document.getElementById(‘chat’).value;

if (message != ”) {

Chat.socket.send(message);

document.getElementById(‘chat’).value = ”;

}

});

var Console = {};

Console.log = (function(message) {

var console = document.getElementById(‘console’);

var p = document.createElement(‘p’);

p.style.wordWrap = ’break-word’;

p.innerHTML = message;

console.appendChild(p);

while (console.childNodes.length > 25) {

console.removeChild(console.firstChild);

}

console.scrollTop = console.scrollHeight;

});

Chat.initialize();

document.addEventListener(“DOMContentLoaded”, function() {

// Remove elements with ”noscript” class - 

 is not allowed in XHTML

var noscripts = document.getElementsByClassName(“noscript”);

for (var i = 0; i 

noscripts[i].parentNode.removeChild(noscripts[i]);

}

}, false);

Seems your browser doesn’t support Javascript! Websockets rely on Javascript being enabled. Please enable

Javascript and reload this page!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值