Javascript 为什么此WebSocket函数返回太多消息?
我在后端使用Ruby gemsJavascript 为什么此WebSocket函数返回太多消息?,javascript,ruby,websocket,sinatra,Javascript,Ruby,Websocket,Sinatra,我在后端使用Ruby gemssinatra和sinatra websocket,前端使用JS 我的后端: get '/' do if(!(request.websocket?)) erb :index else request.websocket do |ws| ws.onopen do settings.sockets << ws end
sinatra
和sinatra websocket
,前端使用JS
我的后端:
get '/' do
if(!(request.websocket?))
erb :index
else
request.websocket do |ws|
ws.onopen do
settings.sockets << ws
end
ws.onmessage do |msg|
EM.next_tick {
settings.sockets.each{|s|
# p s
s.send(msg)
}
}
end
ws.onclose do
warn("connection closed")
end
end
end
end
第一个console.log()
打印一次test
,但是onmessage
中的一个首先给出两次响应,第二次单击一个按钮时给出三次响应,之后每次单击都会给出更多次响应
为什么会这样?如何使onmessage
中的函数在我每次单击按钮时只给我一次msg
window.onload = function(){
function someFunction(){
var ws = new WebSocket('ws://'+window.location.host+window.location.pathname);
ws.onopen = function(){
var buttons = document.getElementsByClassName('buttons');
[].forEach.call(
buttons,
function(btn){
if(btn!=null){
btn.onclick = function(){
var amt = 11;
ws.send(amt);
console.log(amt);
return false;
};
}
}
);
};
ws.onmessage = function(msg){
console.log(msg);
return false;
};
ws.onclose = function(){
console.log("Connection closed");
return false;
};
}
};