我想在某些事件触发时向node.js服务器发送一些数据。并行地,服务器应该每1秒向客户端发送一些数据。我正在使用socket.io。这是我的代码: 服务器端:
app= require('http').createServer(handler).listen(3000),
io = require('socket.io').listen(app);
// request handler function, will send client file which include sliders and graph
function handler (req, res) {
var reqObj = urr.parse(req.url, true);
var reqPath = reqObj.pathname;
if ('/' == reqPath ) {
res.writeHead(200, {'Content-Type': 'text/html'});
fs.readFile(__dirname + '/client.html', function(err, data) {
if (err) {
res.writeHead(500);
return
res.end('Errorloadingclient.html'); }
res.end(data);
}); } };
var slider1, slider2, slider3, slider4 ;
io.sockets.on('connection', function(socket) {
// receive changed value of slider send by client
socket.on('ValSlider1', function(data){
slider1 = data ;
console.log("Slider 1 Value: " + data); });
// same for three more sliders });
// send received values back to client after every 1 second interval
setInterval(function () {
var data = slider1 + "-" + slider2 + "-" + slider3 + "-" + slider4;
socket.emit('packet', data);
},1000); });
app.maxConnections = 1;
客户方:
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript"
src="http://smoothiecharts.org/smoothie.js"></script>
// slider
<p id="ValSlider1"> Curr Val </p>
<input class = "mySlider1" type="range" name="slider" id="slider-0" value="0" min="0" max="100" />
//类似于另外三个滑块 包
var socket = io.connect('http://localhost');
// send changed value to server
$(".mySlider1").change(function() {
var sVal = $(this).val();
socket.emit('ValSlider1', sVal);
});
//类似于另外三个滑块
socket.on('packet', function (data) {
var valFromServer = data.split('-');
document.getElementById("ValSlider1").innerHTML = valFromServer[0];
});
</script>
现在,只有当我在客户端使用'socket.emit()'两次时才在服务器端获取数据,服务器以1秒的间隔发送数据。
答案 0 :(得分:0)
最后我设法以这种方式做到了, 在服务器端
app= require('http').createServer(handler).listen(3000),
io = require('socket.io').listen(3001);
publisher = require('socket.io').listen(app);
在客户端
var socket = io.connect('http://localhost:3001');
var socket2 = io.connect('http://localhost');
客户端将数据发送到服务器上的“socket”,响应服务器也会在同一端口上发送一些数据。同时,服务器将每隔1秒间隔在3001端口上发布数据,该间隔在客户端上接收到&#34; .on(&#39; data&#39;)&#34; server1的事件。