WebSocket无法在聊天应用程序中工作?

时间:2014-03-31 10:02:27

标签: java sockets websocket

这是我的java类

    public class ServerEndPointDemo
     {
      @OnOpen
       public void handleOpen()
      {
 System.out.print("Connectin is created");
      }
 @OnMessage
      public String handleMessage(String message)
       {
    System.out.print("message from Client = "+message);
    String replyMessage = "echo"+message;
    System.out.print("message send to Client = "+replyMessage);
      return replyMessage;
         }
       @OnClose
      public void handleClose()
       {
System.out.print("Connectin is closed");
      }
    @OnError
     public void handleError(Throwable e)
     {
e.printStackTrace();
      }

     }

这是我的jsp页面

    <!DOCTYPE html>

    <html>
   <head>
     <title>WEB SOCKET 01</title>
     <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width">
    </head>
     <body>
      <form>
      <input type="text" name="t1" id="textMessage">
     <input type="button" value="SendMessage" onclick="sendMessage()" >
     </form>
       <textarea rows="10" cols="20" id="messagesTextArea"></textarea>
       <script type="text/javascript" language="javascript">
       var messagesTextArea = document.getElementById("messagesTextArea");
      var textMessage = document.getElementById("textMessage");
      var webSocket = new                webSocket("ws://localhost:8080/WebSocketPrj01/ServerEndPointDemo");
       webSocket.Onopen = function Message(){processOpen(message);};
         webSocket.Onmessage = function Message(){processMessage(message);};
       webSocket.Onclose = function Message(){processClose(message);};
        webSocket.Onerror = function Message(){processError(message);};
          function processOpen(message)
       {
        messagesTextArea.value +="server Connected....."+"\n"; 
      }

     function processMessage(message)
     {
messagesTextArea.value +="Receive from server....."+message.data+"\n"; 
     }

     function processClose(message)
      {
 webSocket.send("client disconnected");
 messagesTextArea.value +="server DISConnected....."+"\n"; 
     }
      function sendMessage()
     {
        alert("enter");

 if(textMessage.value!=="close")
    {
     alert(textMessage.value);
      webSocket.send(textMessage.value);
      alert("2");
      messagesTextArea.value +="send to server....."+textMessage.value()+"\n"; 
     alert("3");
    textMessage.value="";
   alert("4");
    }
   else{
  alert("else message");
    webSocket.close();
  }

    }
     function processError(message)
      {
 webSocket.send("client disconnected");
 messagesTextArea.value +="error....."+"\n"; 
      }
     </script>
     </body>
     </html>

此行无效 webSocket.send(textMessage.value); 此外,我在检查元素

时在控制台上收到此错误
  

TypeError:webSocket不是构造函数newjsp.jsp:25。

     

TypeError:webSocket未定义

1 个答案:

答案 0 :(得分:2)

应该是:

var webSocket = new WebSocket("ws://localhost:8080/WebSocketPrj01/ServerEndPointDemo");

(“WebSocket”以大写字母开头)。