0

i write a small code.

var app = require('../app');
var debug = require('debug')('PHCServer:server');
var http = require('http');
var pg = require('pg');

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
var server = http.createServer(app);
var io = require('socket.io')(server);

io.on('connection',function(socket){
  socket.on('message',function(data){
    pg.connect(str,function(err,client,done){
       var c = "'"+data.complaint+"',";
       c += "'"+data.symptoms+"'";

        client.query("INSERT INTO Appointment (complaint,symptoms) VALUES ("+c+")",
         function(error,result){
          console.log('result is');
          console.log(data.eid);
          socket.emit('message1','djlksjdslkj'); 
          client.end();
       });
     });
     console.log(data); 
  });
  socket.on('message1',function(data){
    console.log('message1 is');
    console.log(data);

  });
});

from client side i write small code

var socket = io.connect('http://lit-spire-7546.herokuapp.com');
socket.emit("message",obj);

it is inserting data in postgresql but socket.emit not working.can anyone please guideline why socket.emit is not working ??

mathlearner
  • 7,509
  • 31
  • 126
  • 189

1 Answers1

0

For one, you have to wait for the client socket to connect before attempting to use it:

var socket = io.connect('http://lit-spire-7546.herokuapp.com');
socket.on("connect", function() {
    socket.emit("message",obj);
});

Also, if http://lit-spire-7546.herokuapp.com is not the server that your web page came form, then you will have to enable cross origin support on your server.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • there is no issue in emitting.because message emitted thats why it went to server and created the appointment.issue is when i call socket.emit on server side.thats not working .getting my point ?? – mathlearner Apr 05 '15 at 14:16
  • @RiteshMehandiratta - Your client code does not show a listener for the `message1` message. For some reason, you put that listener in the server. But you're sending the message from server to client so if you want to see that message, you have to put the listener in the client code. – jfriend00 Apr 05 '15 at 17:08