简体   繁体   English

socket.io和HTTP node.js中的if / else条件

[英]If/else condition in socket.io and HTTP node.js

I am trying to implement a conditional action for socket.io, using Node.js's HTTP package. 我正在尝试使用Node.js的HTTP包为socket.io实现条件操作。

Basically what i want is, according to the get request, the socket.io to call different function or send different data. 基本上我想要的是根据get请求,调用不同的函数或发送不同的数据的socket.io。

Here is my code: 这是我的代码:

var http = require('http'),
fs = require('fs');

var app = http.createServer(function (request, response) {
fs.readFile("client.html", 'utf-8', function (error, data) {
    response.writeHead(200, {'Content-Type': 'text/html'});
    response.write(data);
    response.end();
});
}).listen(1337);

var io = require('socket.io').listen(app);

io.sockets.on('connection', function(socket) {
socket.on('message_to_server', function(data) {

    http.get("/something", function(res) {
        io.sockets.emit("message_to_client",{ message: data["message"] });
        console.log(data["message"]);
    });

    http.get("/else", function(res) {
        console.log("something else");
    });

});
});

What should i do to implement such feature? 我应该怎么做才能实现这种功能?

I think you are doing it in the wrong way. 我认为您做错了方法。

It can be done like 可以像

io.sockets.on('connection', function(socket) {
   socket.on("something", function(res) {
        socket.emit("message_to_client",{ message: data["message"] });
        console.log(data["message"]);
   });

   socket.on("else", function(res) {
        console.log("something else");
   });
});

and edit the views for route /something so as to emit something when it loads to server. 并编辑route /something的视图,以便在加载到服务器时发出something and do the same for route /else 并对路由/else执行相同的操作

Here you are emiting the custom events to the server according to the page you are in sothat that server can respond/emit accordingly to each route. 在这里,您将根据所进入的页面向服务器发出自定义事件,以便服务器可以相应地响应/发送每个路由。 The other way you are trying doesnt seem to work. 您尝试的另一种方法似乎不起作用。 Sorry if i am wrong. 对不起,如果我错了。

update 更新

in your client side (views) you could have like 在您的客户端(视图)中,您可能会喜欢

view1.html view1.html

var socket = io.connect('http://localhost:8080');
socket.on('connect', function(){
socket.emit('something');
});

socket.on('message_to_client', function (data) {
alert(data);
});

view2.html view2.html

var socket = io.connect('http://localhost:8080');
socket.on('connect', function(){
socket.emit('else');
});

socket.on('message_to_client', function (data) {
alert(data);
});

note 注意

also note that from server if you use io.socket.emit it would broadcast to all connections . 还请注意,如果您使用io.socket.emit从服务器,它将广播到所有连接。 instead use socket.emit (in your case object is socket ) to send to the perticular connection 而是使用socket.emit (在您的情况下,对象是socket )发送到垂直连接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM