2017-05-11 6 views
0

サーバーサイドコードにメッセージを受信して​​いない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}`) 
}) 

クライアント側コード:

クライアントのdoesntを実行
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」を発し、私が何をやっています違う。

+0

'' socket.on( '接続' ...) 'と' socket.on( '接続' が...)を交換し、それが動作するはずです – mk12ok

答えて

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) 
})