javascript没有为websocket连接触发onmessage / onopen方法

时间:2014-04-06 07:53:15

标签: java javascript websocket

我正在尝试通过Web套接字实现基本的服务器客户端通信。我在我的服务器上有控制台打印,告诉我何时打开一个连接并收到消息。一旦我按下我的客户端上的发送按钮,我就会从服务器上获得“收到的东西”控制台打印但是客户端的onopen功能(粘贴在下面)不会被触发。其他功能也是如此。我做错了什么?

这是我的代码:

html age的客户端代码:

 <script type="text/javascript">
        document.getElementById("msg").value = "Website Opened";
        var ws = new WebSocket("ws://localhost:8080/PushServlet/echo");

    ws.onopen = function () 
    {
    document.getElementById("msgArea").textContent += "Connection Opened \n";
    };

    function connect()
    {
    ws = new WebSocket("ws://localhost:8080/PushServlet/echo");
    var wss = "ws = " + ws.toString();
    document.getElementById("msgArea").textContent += wss;
    };

    ws.onmessage = function(message) 
    {
        document.getElementById("msgArea").textContent += message.data;              
    };

   function postToServer() 
    {
        if(ws == null)
    {
        document.getElementById("msgArea").textContent += "Connection Null \n";
    }
        ws.send(document.getElementById("msg").value);
        document.getElementById("msg").value = "";
    };

   ws.onclose = function(evt) 
   {
    document.getElementById("msgArea").textContent += "closed";
   };

   function updateTextBox() 
    {
        document.getElementById("msg").value = "Blah Blah Blah";
    };

    function closeConnect() 
    {
    document.getElementById("msg").value = "Blah Blah Blah";
        ws.close();
    };
    </script>
    </head>

    <body>
        <div>
            <textarea rows="4" cols="100" id="msgArea" readonly></textarea>
    </div>
    <div>
        <input id="msg" type="text" value="Website Opened 1" />
        <button type="submit" id="sendButton" onclick="postToServer()">Send</button>
        <button type="submit" id="update_button" onclick="connect()" > Update </button>
     </div>
    </body>
    </html>

websocket连接的服务器端代码:

package com.servlet.pushServlet;

import java.io.IOException;

import javax.websocket.OnMessage;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/echo")
public class EchoEndpoint {
   @OnMessage
   public void onMessage(Session session, String msg) {
      try {
         session.getBasicRemote().sendText("Send something");
         System.out.println("Some thing recieved");
         session.close();
      } catch (IOException e) {  }
   }
}

0 个答案:

没有答案