NorCalKnockOut
NorCalKnockOut

Reputation: 878

io.sockets is defined, but socket isn't

io.sockets.emit works fine and sends the message out to all connected sockets, but socket.emit doesn't work and socket is undefined.

Any ideas?

var app = require('express')();
  var http = require('http').Server(app);
  var io = require('socket.io')(http);
  var net = require('net');
  var express = require('express');
  var sqlite3 = require('sqlite3').verbose();
  var db = new sqlite3.Database('test-db.db');


  var tools = require('./public/js/tools.js');
  var app_tools = require('./public/js/app.js');

  db.serialize(function() {
          db.run("CREATE TABLE if not exists names (info TEXT)");
  });

  app.use(express.static(__dirname + '/public'));

  app.get('/', function(req, res){
    res.sendFile(__dirname + '/index.html');
  });

  io.on('connection', function(socket){
          socket.on('chat message', function(msg){
      console.log('message from geomon-ui: ' + msg);
      if(msg.indexOf("add") >= 0)
      {
          console.log("adding to database table");
        var words = msg.split(' ');
        console.log("name to add = " + words[1]);
        var insertString = "INSERT into names  (info) VALUES ('" +
  words[1] + "')";
          db.run(insertString);
          db.each("SELECT rowid AS id, info FROM names", function(err, row) {
          console.log(row.id + ": " + row.info);
          });
      }
      else if(msg.indexOf("delete") >= 0)
      {
        console.log("deleting from database table");
        var words = msg.split(' ');
        console.log("name to delete = " + words[1]);
        var deleteString = "DELETE from names WHERE (info) = '" + words[1] + "'";
        console.log(deleteString);
        db.run(deleteString);
        db.each("SELECT rowid AS id, info FROM names", function(err, row) {
          console.log(row.id + ": " + row.info);
        });
      }
      else if(msg == "print")
      {
          db.each("SELECT rowid AS id, info FROM names", function(err, row) {
          console.log(row.id + ": " + row.info);
          });
      }
      else if(msg == "status off")
      {
        console.log(socket);
        console.log(io.sockets);

          socket.emit("colorChange", { status: 'off' });
      }
      else if(msg == "status on")
      {
       io.sockets.emit("colorChange", { status: 'on' });
      }
      else if(msg == "hello")
      {
          tools.hello();
      }
      else if(msg == "send")
      {
        var HOST = '10.1.1.200';
        var WRITEPORT = 8889;
        var socket = net.createConnection(WRITEPORT, HOST);
        socket.write('status=Encrypt input=Kyle');

        var READPORT  = 8888;
        var tcpServer = net.createServer(function(sock) {
            console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);
            sock.on('data', function(data) {
                console.log('DATA ' + sock.remoteAddress + ': ' + data);
                var cont = data.toString();
                io.sockets.emit("printMessage", { content: cont });
            });

            sock.on('uncaughtException', function(err) {
              console.log(err);
            });

            sock.on('error', function() {
              console.log("error");
            });

            sock.on('end', function() {
              tcpServer.close();
            });


        }).listen(READPORT, HOST);
      }
    });
  });

  http.listen(3000, function(){
    console.log('listening on localhost:3000');
  });

Edit: Here is the exact code Im running. If you run this, then go to the input text box and type "status off" you can see that socket is undefined.

Upvotes: 0

Views: 78

Answers (1)

robertklep
robertklep

Reputation: 203359

The problem is this line:

var socket = net.createConnection(WRITEPORT, HOST);

In Javascript, variables are "hoisted" to the "top" of their scope.

In your case, you're doing something similar to this:

socket.on('chat message', function(msg) {
  var socket; // this will clobber the previous 'socket' variable!

  if (msg == "status off") {
    // socket _will_ be undefined here!
  } ...
  else if (msg == "send") {
    socket = net.createConnect(...);
  }
});

if blocks don't start a new scope, so any variable declarations in if blocks are hoisted.

Quickest solution: don't name that variable socket, but call it something else.

Upvotes: 1

Related Questions