个性化阅读
专注于IT技术分析

如何实现websocket长连接发送消息到前端?

如何实现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 = textArea.value;
    if(data === undefined || data === null || data === "" || data === "\n")
        return;
    textArea.value = "";
    var message = new Object();
    message.sender = sender;
    message.receiver = receiver;
    message.date = timeFormat(new Date().getTime());
    message.data = 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代码如下:

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");
    }

}
赞(0) 打赏
未经允许不得转载:srcmini » 如何实现websocket长连接发送消息到前端?
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!

 

觉得文章有用就打赏一下文章作者

微信扫一扫打赏