2017-06-28 27 views
0

我有簡單的聊天Java的網絡套接字,但這是行不通的,我不明白爲什麼。如何用tomcat啓動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

你沒有提到websocket中的appname。

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

我覺得這是你的錯字錯

+0

,你的意思是對應用程序的名字?這是tomcat運行/調試配置的名稱,或maven項目中的模塊名稱或更多? – Pavel

+1

平均項目名稱,你只是提到頁面名稱,但在localhost:8080有很多項目,所以定義項目,其中包含您的索引頁。 –

+0

我添加/ web-base /由於這個模塊的名稱,它打包在戰爭,但錯誤到js控制檯:chat.html:27 WebSocket連接到'ws:// localhost:8080/web-base/index'失敗:錯誤在WebSocket握手期間:意外的響應代碼:404 – Pavel

相關問題