如何实现websocket长连接发送消息到前端?结合SSH框架websocket长连接如何实现?有没有java后端和前端代码的实现实例?
这里websocket长连接客户端使用java,客户端使用javascript的websocket,实现的是客户端和客户端交流的长连接,其中websocket前端客户端部分代码如下:
initSocket();
window.onload = function () {
centerWindow();
var date = new Date();
var time = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" +date.getMilliseconds();
alert(time);
}window.onresize = centerWindow;
document.onkeydown = keyDownSearch;
window.onbeforeunload = function (ev) {
closeSocket();
}function centerWindow() {
var window = document.getElementById("window");
var marginTop = (document.body.clientHeight - window.style.height)/2;
window.style.marginTop = marginTop + "px";
}function keyDownSearch(e) {
if(!sender || !receiver)
return true;
var theEvent = e || window.event;
var code = theEvent.keyCode || theEvent.which || theEvent.charCode;
if (code === 13) {
sendMessage();
return false;
}
return true;
}function sendMessage() {
var textArea = document.getElementById("input_area");
var data = http://www.srcmini.com/textArea.value;
if(data === undefined || data === null || data ==="" || data =http://www.srcmini.com/=="\n")
return;
textArea.valuehttp://www.srcmini.com/= "";
var message = new Object();
message.sender = sender;
message.receiver = receiver;
message.date = timeFormat(new Date().getTime());
message.data = http://www.srcmini.com/data;
var json = JSON.stringify(message);
socket.send(json);
addMessage(false,message);
}function closeSocket() {
if(!sender || !receiver)
return;
socket.close();
}function initSocket() {
if(!sender || !receiver)
return;
var url ="ws://localhost:8080/webserver/chat/" + sender;
if(window.WebSocket){
socket = new WebSocket(url);
}
else if(window.MozWebSocket){
socket = new MozWebSocket(url);
}
else{
alert("invalid.");
}
socket.onopen = function (obj) {
console.log("connection open: " + obj.readyState);
}
socket.onclose = function (obj) {
console.log("connection close: " + obj.readyState);
}
socket.onerror = function (obj) {
console.log("connection error: " + obj.reason);
}
socket.onmessage = function (obj) {
var message = JSON.parse(obj.data);
addMessage(true,message)
}
}
【如何实现websocket长连接发送消息到前端()】服务端websocket代码如下:
package com.chatserver.controller;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Date;
import java.util.concurrent.CopyOnWriteArraySet;
@ServerEndpoint("/chat/{userId}")
public class ChatHandler {private static CopyOnWriteArraySet<
ChatHandler> handlers = new CopyOnWriteArraySet<
>();
private Session session;
@OnOpen
public void onOpen(@PathParam("userId")String userId, Session session){
this.session = session;
handlers.add(this);
System.out.println("current size: " + handlers.size());
}@OnClose
public void onClose(Session session, CloseReason closeReason){
handlers.remove(this);
System.out.println("current size: " + handlers.size());
}@OnMessage
public void onMessage(Session session,String text){
System.out.println("receive message: " + text);
for(ChatHandler handler : handlers){
handler.session.getAsyncRemote().sendText("server message: " + new Date().toString());
}
}@OnError
public void onError(Session session,Throwable error){
System.out.println("onError");
}}
推荐阅读
- 如何将使用JavaScript请求到的JSON数据根据时间进行重新排序()
- JavaScript的变量作用域是什么(如何理解变量作用域?)
- 如何使用CSS使div垂直滚动()
- Perl哈希详细解读
- C和Dart之间的区别
- jQuery | jQuery.support属性用法详细解读
- Python中的多线程详细解读1
- C-SCAN磁盘调度算法详细介绍
- PHP chr()函数用法介绍