Web socketing中java脚本中的代码错误

时间:2014-10-23 04:59:30

标签: javascript websocket

我创建了一个JavaScript代码,用于向Web套接字发送聊天消息,但每条消息都会创建一个新连接。所以每次消息都会回复两次。我需要一个处理每个动作的函数。

问题是我无法从另一种方法访问方法的局部变量:(

function WebSocketTest()
{
  if ("WebSocket" in window)
  {
     var text=f.input_text.value;
     var ws = new WebSocket("ws://localhost:8080/Sobin");
     ws.onopen = function()
     {
        ws.send(text);
     };
     ws.onmessage = function (evt) 
     { 
          var i= evt.data;         
          div = document.createElement('div'); 
          $(div).addClass("b_post").html("<p>"+i+"</p>");              
          $("#content_area").prepend(div);
     };
     ws.onclose = function()
     { 
        alert("Connection is closed..."); 
     };
  }
  else
  {
     // The browser doesn't support WebSocket
     alert("WebSocket NOT supported by your Browser!");
  }
}

3 个答案:

答案 0 :(得分:3)

将ws创建为全局变量并使其等于false。如果它等于false,则仅将ws设置为websocket。在连接关闭时将ws设置为false。应该工作;)

编辑: 如果您真的不想在函数外部进行编码,请使用本机窗口对象在函数内部创建全局变量。如果ws不存在,则可以使用if(!ws)作为初始化ws的条件,等于null,undefined或false。使用window.ws将其设置为全局变量。在关闭连接时,您仍然需要将ws设置为undefined(可能优于false)。

答案 1 :(得分:0)

我得到了这个答案..我使用Jquery

更改了代码

虽然页面加载时间也创建了一个Connection而不是每次创建

var ws = new WebSocket("ws://localhost:8080/Sobin");

。按按钮单击时间仅运行发送操作 代码ID

$(document).ready(function() {

  if ("WebSocket" in window)
  {

     var ws = new WebSocket("ws://localhost:8080/Sobin");
     ws.onopen = function()
     {
     };
     ws.onmessage = function (evt) 
     { 

          var i= evt.data;         
          div = document.createElement('div'); 
          $(div).attr('id','talkbubble').html("<p>"+i+"</p>");              
          $("#content_area").append(div);
     };
  ws.onclose = function()
     { 
        // websocket is closed.
        alert("Connection is closed..."); 
     };
  }
  else
  {
     // The browser doesn't support WebSocket
     alert("WebSocket NOT supported by your Browser!");
  }
$('#send_button').click(function() {
  var text=f.fname.value;
  ws.send(text);
});
});

答案 2 :(得分:0)

在此修改后的代码中,连接已关闭。

require 'em-websocket'

EM.run do

    @clients = []
   EM::WebSocket.start(:host => '0.0.0.0', :port => '8080') do |ws|
    ws.onopen do |handshake|
            @clients << ws
            @name=handshake.path
            @name=@name.sub("/" ,"")
            puts "open";
        end
    ws.onclose do
            ws.send "Closed."//Closing the each connection
            puts "Closed."
            @clients.delete ws
        end

    ws.onmessage do |msg|

                @clients.each do |socket|
                socket.send "#{@name}:"+msg
              end

        end
   end
end