套接字毫无意义?

时间:2015-06-22 05:02:24

标签: javascript node.js sockets

我正在使用' ws' Node.js的库。

我可以编写代码,将数据从我的服务器发送到我的客户端,发布日期和时间更新,并在单击按钮时关闭套接字;



var wss = new WebSocketServer({server: server});
console.log("WebSocket server created");

wss.on('connection', function(socket) {
        // SEND DATE AND TIME EVERY SECOND
	var interval = setInterval(function() {
		socket.send(JSON.stringify(new Date()), function() {});
	}, 1000);

	console.log("WebSocket connection opened");

	socket.on('close', function() {
		console.log("WebSocket connection closed");
		clearInterval(interval);
	});
});






<html>
  <head>
    <script>
      var host = location.origin.replace(/^http/, 'ws')
      var ws = new WebSocket(host);
      ws.onmessage = function (event) {
        var li = document.createElement('li');
        li.innerHTML = JSON.parse(event.data);
        document.querySelector('#pings').appendChild(li);
      };

      function pressed() {
        // CLOSE STREAM
        ws.close();
      }
    </script>
  </head>

  <body>
    <h1>Pings</h1>
    <form name="form1" method="post" action="">
    <input type="button"  value="Call server" onClick="pressed()">
    <ul id='pings'></ul>
  </body>
</html>
&#13;
&#13;
&#13;

但由于某种原因,我无法找到一种方法将数据发送回服务器,然后调用控制台进行打印&#34;按下!&#34;管他呢。这是一种限制,因为它不是双向的,而是套接字似乎是单向流。

像这样;

&#13;
&#13;
    var wss = new WebSocketServer({server: server});
    console.log("WebSocket server created");

    wss.on('connection', function(socket) {
            // SEND DATE AND TIME EVERY SECOND
    	var interval = setInterval(function() {
    		socket.send(JSON.stringify(new Date()), function() {});
    	}, 1000);

    	console.log("WebSocket connection opened");

        // LOOK FOR 'pressed' BEING SENT
      	socket.on('pressed', function() {
		    console.log("Pressed!");
		    socket.close();
	    });
      
    	socket.on('close', function() {
    		console.log("WebSocket connection closed");
    		clearInterval(interval);
    	});
    });
&#13;
&#13;
&#13;

&#13;
&#13;
<html>
  <head>
    <script>
      var host = location.origin.replace(/^http/, 'ws')
      var ws = new WebSocket(host);
      ws.onmessage = function (event) {
        var li = document.createElement('li');
        li.innerHTML = JSON.parse(event.data);
        document.querySelector('#pings').appendChild(li);
      };

      // SEND 'pressed' TO SERVER
      function pressed() {
        ws.send('pressed');
      }
    </script>
  </head>
  
  <body>
    <h1>Pings</h1>
    <form name="form1" method="post" action="">
    <input type="button"  value="Call server" onClick="pressed()">
    <ul id='pings'></ul>
  </body>
</html>
&#13;
&#13;
&#13;

我错过了什么,刚开始学习插座,感觉就像我试图用棉花勺在砖墙上挖洞。

1 个答案:

答案 0 :(得分:1)

客户端无法在套接字上触发任意事件。它始终是message事件。使用相同的客户端,在connection处理程序中尝试此服务器代码:

    socket.on('message', function(data) {
        // data === "pressed", since that's what the client sent
        console.log("Pressed!");
        socket.close();
    });