如何用tomcat启动web-socket应用程序?

时间:2017-06-28 21:44:27

标签: java tomcat websocket

我与Java web-socket进行了简单的聊天,但这不起作用,我不明白为什么。

服务器类哪个简单的写日志:

@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());
    }
}

我有一个简单的客户:

<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/index");

        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>

但是当我启动tomcat时,我有代码404。我认为在我的项目中没有足够的部分(类或一些配置文件)。

这是我项目的结构: enter image description here

所有类ChatServer标记为从未使用过。我认为这不正常。我的项目成功运行中缺少什么?帮我解决这个问题。谢谢。

1 个答案:

答案 0 :(得分:1)

您没有在websocket中提及appname。

                                                    //here
var chatClient = new WebSocket("ws://localhost:8080/appname/index");

我认为这是你的拼写错误