套接字发出方法在客户端上不起作用-Node JS

时间:2018-11-14 10:25:10

标签: javascript node.js sockets socket.io

我正在使用Node JS和客户端上的纯Javascript进行Socket IO。建立了两端的连接后,消息已成功从服务器传递到客户端,但是单击按钮后,套接字不会向服务器发出任何消息,我不知道这是什么问题。

服务器端代码

df.columns

  

以上代码发送成功向客户端发出“嗨”。

客户端代码

const phantom = require('phantom');
const ev = require('events');
const event = new ev.EventEmitter();
const mysql = require("mysql");
const ms_connect = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'scrapper_db'
});
const express = require("express");
const app = express();
const internetAvailable = require("internet-available");
const body_parser = require('body-parser');
const server = app.listen(8080, function() {
  console.log('Listening on 8080');
});
const io = require("socket.io").listen(server);

/*----------------------------------------------------------------------------------------------------------
    
            B A S I C   A P P   R O U T I N G    F U N C T I O N S
    
----------------------------------------------------------------------------------------------------------*/
app.use(express.static(__dirname + "/public"));
app.use(body_parser.json());

app.get("/", function(req, res) {

  res.sendFile("/index.html");

})
/*----------------------------------------------------------------------------------------------------------
    
                         G L O B A L   F U N C T I O N S
    
----------------------------------------------------------------------------------------------------------*/
function Globals() {

  this.socketConnection = async function() {
    let p = new Promise(function(res, rej) {
      io.on("connection", function(socket) {
        if (socket.connected) {
          res(socket);
        } else {
          rej("Socket Connection Error !");
        }
      })
    })
    return await p;
  }
  this.databaseConnection = async function() {
    let p = new Promise(function(res, rej) {
      ms_connect.connect(function(err) {
        if (err) {
          rej({
            success: false,
            data: err
          });
        } else {
          res({
            success: true
          });
        }
      })
    })
    return await p;
  }
}





/*----------------------------------------------------------------------------------------------------------
    
                        G L O B A L   F U N C T I O N S
    
----------------------------------------------------------------------------------------------------------*/
function ScrapJobs(socket) {

  var _this = this;

  this.init = function() {
    console.log(socket.client.id);
  }

}

var GL = new Globals();

GL.socketConnection().then(function(s) {
  s.emit("Hi");
  s.on("Nady", function() {
    console.log("I am from client");
  })
  new ScrapJobs(s).init();
})

  

在客户端脚本中,当我单击按钮时,它不会发出“ Nady”事件。

0 个答案:

没有答案