2016-06-19 77 views
0

雖然試圖設置一個簡單的NodeJS服務器和Socket.io客戶端來測試WebSockets的東西,但我偶然發現了一些愚蠢的東西。我很肯定這是愚蠢的我已經完成了,因爲我曾經使用過NodeJS/Socket.io,並且從未遇到過這個問題。NodeJS/Socket.io沒有收到來自客戶端的事件

使用下面的代碼,我可以從客戶端上的服務器接收到'tick'事件,但服務器似乎無法從客戶端接收'ping'事件。 'tick'用於確保server-> client工作,'ping'用於測試client-> server。

採用了最新Socket.io(1.4.6)和表達(4.14.0)

server.js:

var express = require('express'); 
var app = require('express')(); 
var server = require('http').createServer(app); 
var sio = require('socket.io')(server); 
var path = require('path'); 

app.use(express.static(path.join(__dirname, 'public_html'))); 

// Socket.io 
sio.on('connection', (socket) => { 
    // Store socket ID 
    var socketID = socket.conn.id; 

    // Log connection 
    console.log('Connection:', socketID); 

    // Ping event 
    socket.on('ping', (message) => { 
     console.log('Ping:', socketID, '-', (message || '(no message>')); 
    }); 

    // Tick event 
    var tick = function(){ 
     var now = new Date().getTime().toString(); 
     socket.emit('tick', now); 
    } 
    setInterval(tick, 5000); 

    // Disconnect event 
    socket.on('disconnect',() => { 
     console.log('Disconnected:', socketID); 
    }); 
}); 

server.listen(4100,() => { 
    console.log('Listening on :4100'); 
}); 

的index.html:

<!DOCTYPE html> 
<html> 
<head> 
    <title>Websockets Benchmark</title> 
</head> 
<body> 
    <script src="/socket.io/socket.io.js"></script> 
    <script> 
     // Socket.io 
     var sio = io(); 

     // Connection event 
     sio.on('connect',() => { 
      console.log('Connected'); 

      sio.emit('ping', 'on connect'); 
     }); 

     // Tick event 
     sio.on('tick', (time) => { 
      console.log('Tick', time); 
     }); 

     // Error event 
     sio.on('error', (e) => { 
      console.error(e); 
     }); 
    </script> 
</body> 

回答

0

無法確定是否由Socket.io執行了ping事件,o R下面的命令行導致的一個問題:

console.log('Ping:', socketID, '-', (message || '(no message)')); 

無論哪種方式,通過改變事件名稱ev:ping(這是無論如何更容易理解),並簡化該行它的固定! :)

0

希望我明白你的問題... 我做了一些工作與聊天使用socket.io所以馬ybe它會幫助你。 那就是:

<div class="searchBox" style="height: 600px ; width: 500px"> 
     <div style=";width:400px;border-right:1px solid black;;overflow:scroll-y;"> 
     <b style="color: black ;text-decoration: underline">USERS:</b> 
     <div id="users" style="color: black"></div> 
     </div> 
     <div style=";width:300px;height:250px;overflow:scroll-y;padding:10px;"> 
     <b style="color: black ; text-decoration: underline">CONVERSATION:</b> 
     <div id="conversation" style="color: black"></div> 
     <input id="data" style="width:200px;" /> 
     <button id="datasend" style="color: #0f0f0f;">send</button> 
     </div> 

和JS:

var socket = io.connect('http://localhost:8080'); 
    // on connection to server, ask for user's name with an anonymous callback 
    socket.on('connect', function(){ 
     // call the server-side function 'adduser' and send one parameter (value of prompt) 
     socket.emit('adduser', prompt("What's your name?")); 
    }); 
    // listener, whenever the server emits 'updatechat', this updates the chat body 
    socket.on('updatechat', function (username, data) { 
     $('#conversation').append('<b>'+username + ':</b> ' + data + '<br>'); 
    }); 
    // listener, whenever the server emits 'updateusers', this updates the username list 
    socket.on('updateusers', function(data) { 
     $('#users').empty(); 
     $.each(data, function(key, value) { 
      $('#users').append('<div>' + key + '</div>'); 
     }); 
    }); 
    // on load of page 
    $(function(){ 
     // when the client clicks SEND 
     $('#datasend').click(function() { 
      var message = $('#data').val(); 
      $('#data').val(''); 
      // tell server to execute 'sendchat' and send along one parameter 
      socket.emit('sendchat', message); 
     }); 
     // when the client hits ENTER on their keyboard 
     $('#data').keypress(function(e) { 
      if(e.which == 13) { 
       $(this).blur(); 
       $('#datasend').focus().click(); 
      } 
     }); 
    }); 

服務器:

var app = require('./app'); 
var http = require('http'); 
var server = http.createServer(app); 
var io = require('socket.io').listen(server); 

server.listen(8080, function() { 
    console.log("Gym Project is listening to: http://127.0.0.1:8080"); 
}); 

// routing 
app.get('/', function (req, res) { 
    res.sendfile(__dirname + '/index.html'); 
}); 


// usernames which are currently connected to the chat 
var usernames = {}; 

io.sockets.on('connection', function (socket) { 

    // when the client emits 'sendchat', this listens and executes 
    socket.on('sendchat', function (data) { 
     // we tell the client to execute 'updatechat' with 2 parameters 
     io.sockets.emit('updatechat', socket.username, data); 
    }); 

    // when the client emits 'adduser', this listens and executes 
    socket.on('adduser', function(username){ 
     // we store the username in the socket session for this client 
     socket.username = username; 
     // add the client's username to the global list 
     usernames[username] = username; 
     // echo to client they've connected 
     socket.emit('updatechat', 'SERVER', 'you have connected'); 
     // echo globally (all clients) that a person has connected 
     socket.broadcast.emit('updatechat', 'SERVER', username + ' has connected'); 
     // update the list of users in chat, client-side 
     io.sockets.emit('updateusers', usernames); 
    }); 

    // when the user disconnects.. perform this 
    socket.on('disconnect', function(){ 
     // remove the username from global usernames list 
     delete usernames[socket.username]; 
     // update list of users in chat, client-side 
     io.sockets.emit('updateusers', usernames); 
     // echo globally that this client has left 
     socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected'); 
    }); 
}); 

這與一些客戶一個非常簡單的聊... 可能它幫助:)

+0

謝謝 - 你的代碼並沒有引導我直接回答,但我認爲我的事件名稱與Socket.io的名稱相沖突 – ToshNeox

相關問題