drztpx8735
drztpx8735
2012-09-07 22:25

Javascript连接到websocket

已采纳

Following up form my last question -

var socket;
if ("WebSocket" in window)
  {
     alert("WebSocket is supported by your Browser!");
     // Let us open a web socket
   socket = new WebSocket("ws://localhost:10001");
  }

socket.onopen() = function(){
    alert("Connection Opened");
}


socket.onmessage() = function(msg){
    alert(msg);
}

I can connect to the server with telnet but I can't seem to connect using Javascript, why is this?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • douxin5953 douxin5953 9年前

    Because WebSocket is not a normal, general-purpose socket. It requires the server on the remote end to conform to a very specific handshake defined by the WebSocket protocol. If your server does not implement this protocol, WebSocket cannot connect to it.

    Additionally, as Rocket points out, your code is currently attempting to call socket.onopen() and assign a value to the function call. Lose the parentheses.

    点赞 评论 复制链接分享