按键盘时的WebSocket事件

时间:2015-10-30 19:23:52

标签: javascript jquery websocket

我尝试让客户端在按下特定键盘时向服务器发送一个字符

这是我的代码:

var connection = new WebSocket('ws://localhost:8001');

$(document).keypress(function(e){ // pressing key 
  if(e.keyCode == 119){ // w 
    $("#d-up").css("background-color","#404d4d","opacity","50%"); // hover effect 
      connection.onmessage = function (event) {  //websocket event 
        connection.send("W");
      };
    }
});

$(document).keyup(function(e){  
    $(".button").css("background-color","#1d2323");
  });

服务器和客户端已连接但按下w时未发送任何消息。感谢你的帮助。

谢谢

1 个答案:

答案 0 :(得分:1)

In your code you are not sending anything when the key is pressed, you are indicating than if you get a message, then send "W". You have to call send directly. $(document).keypress(function(e){ // pressing key if(e.keyCode == 119){ // w $("#d-up").css("background-color","#404d4d","opacity","50%"); // hover effect connection.send("W"); } });