Java EE Websockets

Posted

技术标签:

【中文标题】Java EE Websockets【英文标题】: 【发布时间】:2020-07-27 01:19:19 【问题描述】:

Websockets,无法建立连接。 我可以覆盖方法 OnClose、OnMessage、OnOpen 等吗? 在@ServerEndpoint Annotation 中添加“value =”有什么区别?

如何使用 RoomID 作为参数?

OnOpen(Session session, @PathParam "roomID" String roomID)?


EchoServer.java

import java.io.IOException;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import javax.ws.rs.PathParam;

@ServerEndpoint(value = "/echo/roomID") 
public class EchoServer 

    @OnOpen
    public void onOpen(Session session)
        String roomID = session.getUserProperties().get("roomID").toString();
        session.getUserProperties().put("roomID", roomID);
        SessionHandler.addSession(session, roomID);

        System.out.println(session.getId() + " has opened a connection"); 
        try 
            session.getBasicRemote().sendText("Connection Established");
         catch (IOException ex) 
            ex.printStackTrace();
        
    

    @OnMessage
    public void onMessage(String message, Session session)
        System.out.println("Message from " + session.getId() + ": " + message);
        try 
            session.getBasicRemote().sendText(message);
         catch (Exception ex) 
            ex.printStackTrace();
        
    

    @OnClose
    public void onClose(Session session, String roomID)
        SessionHandler.removeSession(session, roomID);
        System.out.println("Session " +session.getId()+" has ended");
    

SessionHandler.java

import java.util.HashMap;
import java.util.Map;
import javax.websocket.Session;

public class SessionHandler 
    private static final Map<String, Session> sessions = new HashMap<>();

    public static void addSession(Session session, String roomID)
        sessions.put(roomID, session);
    

    public static void removeSession(Session session, String roomID)
        sessions.remove(roomID, session);
    

    public static void sendToSession(Session session, String message)
          System.out.println("Message from " + session.getId() + ": " + message);
        try 
            session.getBasicRemote().sendText(message);
         catch (Exception ex) 
            ex.printStackTrace();
        
    

index.html

<!DOCTYPE html>

<html>
    <head>
        <title>Echo Chamber</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width">
    </head>
    <body>

        <div>
            <input type="number" id="roomID"/>
            <input type="text" id="messageinput"/>
        </div>
        <div>
            <button type="button" onclick="openSocket();" >Open</button>
            <button type="button" onclick="send();" >Send</button>
            <button type="button" onclick="closeSocket();" >Close</button>
        </div>
        <!-- Server responses get written here -->
        <div id="messages"></div>

        <!-- Script to utilise the WebSocket -->
        <script type="text/javascript">

            var webSocket;
            var messages = document.getElementById("messages");


            function openSocket()
                if(webSocket !== undefined && webSocket.readyState !== WebSocket.CLOSED)
                   writeResponse("WebSocket is already opened.");
                    return;
                
                webSocket = new WebSocket("ws://localhost:8080/EchoChamber/echo/"+document.getElementById("roomID").value+"");    


                webSocket.onopen = function(event)
                    if(event.data === undefined)
                        return;

                    writeResponse(event.data);
                ;

                webSocket.onmessage = function(event)
                    writeResponse(event.data);
                ;

                webSocket.onclose = function(event)
                    writeResponse("Connection closed");
                ;
            

            function send()
                var text = document.getElementById("messageinput").value;
                webSocket.send(text);
            

            function closeSocket()
                webSocket.close();
            

            function writeResponse(text)
                messages.innerHTML += "<br/>" + text;
            

        </script>

    </body>
</html>

【问题讨论】:

【参考方案1】:

好的,看起来像默认方法

onClose(Session session)

应该只接受 1 个参数,我的方法

onClose(Session session, String roomID) 

错了。它修复了使用默认方法的所有问题

【讨论】:

以上是关于Java EE Websockets的主要内容,如果未能解决你的问题,请参考以下文章

请问Java ee与Javaweb 有啥区别

终极Java版本表(J2EE、Java EE、Servlet、JSP、JSTL)

java ee 工作方面的问题如下:

Java EE Web 配置文件与 Java EE 完整平台

Java EE 课程作业(third)- 关于 Java EE的思维导图

使用 Java EE 设计模式的示例 Java EE 项目