socket.io没有在服务器上接收消息

时间:2017-05-11 18:48:07

标签: node.js sockets websocket socket.io

服务器端代码

const express = require('express')
const app = express()
const server = require('http').Server(app)
const io = require('socket.io')(server)
io.once('connection', function (socket) {
  console.log(`New connection`)
  socket.emit('hello', 'hello from the server')
  socket.on('clientData', (data) => {
    console.log(data)
  })
})
server.listen(3000, () => {
  console.log(`Server started: http://localhost:${port}`)
})

客户端代码:

var socket = io()
var hello = 'Hello server'
socket.on('connection', function() {
    console.log('established connection')
    socket.emit('clientData', hello)
})
socket.on('hello', function(data) {
  console.log(data)
})

运行时,客户端不会发出' clientData'出于某种原因,我做错了什么。

1 个答案:

答案 0 :(得分:0)

我认为您在客户端的socket.on("connection",使用是错误的。新客户端加入时,连接事件发生在服务器上。

const express = require('express')
const app = express()
const server = require('http').Server(app)
const io = require('socket.io')(server)
io.on('connection', function (socket) {
  // #2 - This will run for the new connection 'socket' and set up its callbacks
  // #3 - send to the new client a 'hello' message
  socket.emit('hello', 'hello from the server') 
  socket.on('clientData', (data) => {
    // #6 - handle this clients 'clientData'
    console.log(data)
  })
})
server.listen(3000, () => {
  console.log("Server started: http://localhost:${port}")
})

客户端代码:

// #1 - this will connect to the server and send the 'connection' 
var socket = io()
var hello = 'Hello server'
socket.on('hello', function(data) {
  // #4 - 'hello' response after connecting
  console.log(data)
  // #5 - send 'clientData' 
  socket.emit('clientData', hello)
})