如何将web-socket映射到url模式?

时间:2017-06-28 00:55:09

标签: java websocket

我需要映射web-socket。在Servlet中,我使用注释或web.xml进行映射,但是如何为服务器套接字创建url-pattern。如果我的index.html文件夹中有webapp如何确定浏览器的URL模式,该模式将与我的网页相关联?

我有服务器部分:

@ApplicationScoped
@ServerEndpoint(value = "/index")// May be this mapping but it's don't work.
public class ChatServer {
    private static final Logger LOGGER =
            Logger.getLogger(ChatServer.class.getName());

    @OnOpen
    public void onOpen(Session session) {
        LOGGER.log(Level.INFO, "New connection with client: {0}",
                session.getId());
    }

    @OnMessage
    public String onMessage(String message, Session session) {
        LOGGER.log(Level.INFO, "New message from Client [{0}]: {1}",
                new Object[] {session.getId(), message});
        return "Server received [" + message + "]";
    }

    @OnClose
    public void onClose(Session session) {
        LOGGER.log(Level.INFO, "Close connection for client: {0}",
                session.getId());
    }

    @OnError
    public void onError(Throwable exception, Session session) {
        LOGGER.log(Level.INFO, "Error for client: {0}", session.getId());
    }
}

我的index.html

<!DOCTYPE html>
<html>
<head>
    <title>JEE7 WebSocket Example</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script>
        var chatClient = new WebSocket("ws://localhost:8080");

        chatClient.onmessage = function(evt) {
            var p = document.createElement("p");
            p.setAttribute("class", "server");
            p.innerHTML = "Server: " + evt.data;
            var container = document.getElementById("container");
            container.appendChild(p);
        };
        function send() {
            var input = document.getElementById("message");
            var p = document.createElement("p");
            p.setAttribute("class", "client");
            p.innerHTML = "Me: " + input.value;
            var container = document.getElementById("container");
            container.appendChild(p);
            chatClient.send(input.value);
            input.value = "";
        }
    </script>
</head>
<body>
<h1>JEE7 WebSocket Example</h1>
<div id="container">

</div>
<input type="text" id="message" name="message" />
<button type="button" id="send" onclick="send()">Send</button>
</body>
</html>

如何将我的服务器端与index.html相关联并将我的html与浏览器相关联?

1 个答案:

答案 0 :(得分:1)

WS://本地主机:8080 /的contextPath /索引