Java EE Websocket

标签 java websocket

Websockets,无法建立连接。 我可以重写 OnClose、OnMessage、OnOpen 等方法吗? @ServerEndpoint 注解中添加“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>

enter image description here

最佳答案

好的,看起来像默认方法

onClose(Session session)

假设只采用 1 个参数,我的方法

onClose(Session session, String roomID) 

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

关于Java EE Websocket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61205559/

相关文章:

java - 如何在 Android 上使用 Flurry 运行 Robolectric

java - MySQL 从 XML 文件中插入数据

java - 在Java中,如何从类文件中获取抽象语法树?

node.js - 消息上的 Express websockets 获取 cookie 信息

java - Spring 4 - websocket消息stomp处理程序

java - 使用 MySQL 和 JDBC 准备语句缓存

Java8 ScheduledExecutorService.scheduleAtFixedRate()

node.js - 为什么我们在nodejs上的javascript中将http服务器传递给websocket实例?

javascript - Socket.IO 命名空间,调用未定义的函数 .of()

java - Tomcat websocket 回显应用程序