最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Nodejs and webSockets, triggering events? - Stack Overflow

programmeradmin5浏览0评论

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

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.

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.

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 municates with the node server using it as a dispatcher to trigger events on the main index page.

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.

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);
    });
});

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

Here is my client code

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.

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: 'wele to the chat' });
    socket.on('send', function (data) {
        io.sockets.emit('message', data);
    });
});

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.

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

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.

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.

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 municates with the node server using it as a dispatcher to trigger events on the main index page.

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.

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);
    });
});

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

Here is my client code

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.

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: 'wele to the chat' });
    socket.on('send', function (data) {
        io.sockets.emit('message', data);
    });
});

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.

Share edited Jan 17, 2014 at 3:57 Michael Joseph Aubry asked Jan 17, 2014 at 3:02 Michael Joseph AubryMichael Joseph Aubry 13.5k16 gold badges77 silver badges141 bronze badges 7
  • where is your server code? there are two part: client + server side, you just show client side. – Anh Tú Commented Jan 17, 2014 at 3:49
  • Server code is in app.js, I really am starting from scratch though I am trying to understand how I can emit a callback to a different page. Ill post app.js though, it's cookie cutter copy and paste from a mon tutorial. – Michael Joseph Aubry Commented Jan 17, 2014 at 3:55
  • In your console it show: 'io is not defined'. are you sure you include socket.io right? And var socketTwo = io.connect('http://my-server-ip:3000/test.html');? where did you find that? – Anh Tú Commented Jan 17, 2014 at 3:57
  • Well I think it gives me the error because of the route? http://my-server-ip:3000/test.html the server specifically listens to port 3000 I think, so this is why I am asking I am not sure how to trigger events on test.html and receivie a callback on the index – Michael Joseph Aubry Commented Jan 17, 2014 at 4:01
  • just use one instance var socket = io.connect('http://my-server-ip:3000/'); you don't need 2 instances here – Anh Tú Commented Jan 17, 2014 at 4:02
 |  Show 2 more ments

1 Answer 1

Reset to default 4

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.

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);
    });
});

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);
        }
    });

}
发布评论

评论列表(0)

  1. 暂无评论