Nodejs和webSockets,触发事件? [英] Nodejs and webSockets, triggering events?

查看:98
本文介绍了Nodejs和webSockets,触发事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新手,我构建了一个标准的网络聊天应用程序,我看到了nodejs,express,socket.io的强大功能。

I am new to this, I built a standard web chat application and I see the power of nodejs, express, socket.io.

我要做的是触发从手机到网站的事件,比如遥控器。有一个服务器javascript可以监听来自客户端的事件,以及触发这些事件的客户端javascript,如果我错了,这就是我理解的纠正方法。

What I am trying to do is trigger events from a phone to a website, like a remote control. There is server javascript that listens to events from the client, and client javascript that triggers those events, this is how I understand it correct me if I am wrong.

我学到了在聊天应用程序中,我可以从任何地方发送对象,只要它们通过特定端口连接到我的服务器 http:// my-server-ip:3000 / 。基本上所有事件都在索引页面内,连接是索引服务器索引

I learned in the chat app I can send an object from anywhere, as long as they are connected to my server through a specific port http://my-server-ip:3000/. Basically all events are inside the index page, and the connection is index to server to index.

我想学的是如何从外部页面触发事件,我见过像 http:// my-server-ip:3000 / ws 或类似的东西,想法是连接到不是实际索引或网站本身的移动界面,但此界面进行通信节点服务器使用它作为调度程序来触发主索引页面上的事件。

What I am trying to learn is how to trigger events from an external page, I've seen things like http://my-server-ip:3000/ws or something like that, the idea is to connect to a mobile interface that isn't the actual index or website itself, but this interface communicates with the node server using it as a dispatcher to trigger events on the main index page.

基本上我学到的是 index 服务器索引。我不知道怎样才能自定义页面服务器 index

Basically what I have learned was index to server to index. I am not sure how I can go custom-page to server to index.

我在app.js中看到,我的理解是套接字监听发送在客户端然后它发出消息。

I see that in my app.js, my understanding is that the socket listens to sends which is on the client then it emits the message.

io.sockets.on('connection', function (socket) {
    socket.on('sends', function (data) {
        io.sockets.emit('message', data);
    });
});

我尝试创建一个有一个按钮的test.html,我试着听一下,这里是一个截屏。

I tried creating a test.html that has a button on it, I tried listening to it, here is a screen shot.

这是我的客户代码

window.onload = function() {

    var messages = [];
    var socket = io.connect('http://my-server-ip:3000/');
    var socketTwo = io.connect('http://my-server-ip:3000/test.html');
    var field = document.getElementById("field");
    var sendButton = document.getElementById("send");
    var content = document.getElementById("content");
    var name = document.getElementById("name");

    var trigBtn = document.getElementById("trigger-btn");

    socket.on('message', function (data) {
        if(data.message) {
            messages.push(data);
            var html = '';
            for(var i=0; i<messages.length; i++) {
                html += '<b>' + (messages[i].username ? messages[i].username : 'Server') + ': </b>';
                html += messages[i].message + '<br />';
            }
            content.innerHTML = html;
        } else {
            console.log("There is a problem:", data);
        }
    });

        //FROM DEMO
    // sendButton.onclick = sendMessage = function() {
    //     if(name.value == "") {
    //         alert("Please type your name!");
    //     } else {
    //         var text = field.value;
    //         socket.emit('send', { message: text, username: name.value });
    //         field.value = "";
    //     }
    // };

        //I include this javascript with test.html and trigger 
        //this button trying to emit a message to socketTwo
    trigBtn.onclick = sendMessage = function() {
        socketTwo.emit('send', { message: 'String test here' })
    }

}

我确信这都是错的,但希望这是有道理的,有人可以帮我触发从另一个页面触发索引的事件。

I am sure that is all wrong, but hopefully this makes sense and someone can help me trigger events from another page triggering to the index.

这是我的app.js服务器代码

Here is my app.js server code

/**
 * Module dependencies.
 */

var express = require('express')
  , routes = require('./routes')
  , http = require('http');

var app = express();
var server = app.listen(3000);
var io = require('socket.io').listen(server); // this tells socket.io to use our express server

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.static(__dirname + '/public'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
});

app.configure('development', function(){
  app.use(express.errorHandler());
});

app.get('/', routes.index);

app.get('/test.html', function(req, res) {
    res.send('Hello from route handler');
});

io.sockets.on('connection', function (socket) {
    socket.emit('message', { message: 'welcome to the chat' });
    socket.on('send', function (data) {
        io.sockets.emit('message', data);
    });
});

上面发布的所有代码只是测试cookie切割器代码,我从头学习,所以上面的内容可以是完全改变了,它只是作为一个起点。

All code posted above is just testing cookie cutter code, I am learning from scratch so the above can be totally changed, it's just there as a starter point.

推荐答案

这太酷我开始工作,所以我的逻辑是正确。我失踪了一些东西。在这里。

This is so cool I got it to work, so my logic was correct. There were just a few things I was missing. Here it is.

我不会发布所有服务器端的javascript代码,但这是听完端口等后的主要逻辑。

I am not going to post all the server side javascript code, but here is the main logic after listening to the port etc.

// Set a route and in a very dirty fashion I included a script specific
// for this route, earlier I was using one script for both route.
// I also forgot to include the socket.io hence the error in the image above.
app.get('/test', function(req, res) {
    res.send('<script src="/socket.io/socket.io.js"></script><script type="text/javascript" src="javascripts/trigger.js"></script><button id="test" class="trigger-btn">Trigger</button>');
});

// This listens to `send` which is defined in the `test` route
// Upon this action the server emits the message which
// is defined inside the index main route I want stuff displayed   
io.sockets.on('connection', function (socket) {
    socket.on('send', function (data) {
        io.sockets.emit('message', data);
    });
});

这是索引客户端,js脚本的样子

Here is what the index client,js script looks like

window.onload = function() {

    var messages = [];
    var socket = io.connect('http://my-server-ip:3000');
    var content = document.getElementById("content");

    socket.on('message', function (data) {
        if(data.message) {
            messages.push(data);
            var html = '';
            for(var i=0; i<messages.length; i++) {
                html += '<b>' + (messages[i].username ? messages[i].username : 'Server') + ': </b>';
                html += messages[i].message + '<br />';
            }
            content.innerHTML = html;
        } else {
            console.log("There is a problem:", data);
        }
    });

}

这篇关于Nodejs和webSockets,触发事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆