【问题标题】:Emit server to client data in NodeJS在 NodeJS 中将服务器发送到客户端数据
【发布时间】:2019-05-09 03:54:03
【问题描述】:

我无法从服务器向客户端发送数据,对于客户端 js 代码中的 res 变量,我在 console.log 上未定义。

这是我的服务器代码

const express = require('express')
const app = express()
const server = require('http').createServer(app)
const io = require('socket.io')(server)
const path = require('path')

// View
app.use(express.static(path.join(__dirname, '/view')))

// Homepage
app.get('/', function (req, res) {
  res.sendfile(path.join(__dirname + '/view/index.html'))
})

// Socket connection
io.on('connection', function(socket) {

  console.log('----------------------------')
  console.log('connected an user')
  console.log('----------------------------')

  socket.emit('connect', 'datax')

  socket.on('disconnect', function() {
    console.log('disconnected')
    console.log('----------------------------')
  })

})

// Server run
server.listen(3000)

这是我的客户代码

$(document).ready(function(){

  'use strict';

  var socket = io('http://localhost:3000');

  socket.on('connect', function(res) {

    console.log('connected');

    console.log(res);

  })
  .on('disconnect', function() {
    console.log('disconnect');
  });

});

感谢您的帮助。

【问题讨论】:

    标签: node.js socket.io emit


    【解决方案1】:

    查看套接字 io 发射备忘单。here。滚动到底部,您会看到有一些保留字不能用于发出自定义事件。连接就是这样一个词。尝试发出其他事件并在客户端收听。

    【讨论】:

      猜你喜欢
      • 2020-08-17
      • 2022-01-12
      • 1970-01-01
      • 2015-03-05
      • 2015-08-02
      • 1970-01-01
      • 2013-08-13
      • 2013-04-11
      • 2021-12-07
      相关资源
      最近更新 更多