socket.io只能在本地机器上工作,无法从另一台机器连接

时间:2015-03-09 09:45:47

标签: html mysql sockets

var mysql = require('mysql')
// Let’s make node/socketio listen on port 3000
var io = require('socket.io').listen(3000)
// Define our db creds
var db = mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'node'
 })

 // Log any errors connected to the db
 db.connect(function(err){
 if (err) console.log(err)
 })

 // Define/initialize our global vars
 var notes = []
 var isInitNotes = false
 var socketCount = 0

 io.sockets.on('connection', function(socket){
  // Socket has connected, increase socket count
   socketCount++
  // Let all sockets know how many are connected
   io.sockets.emit('users connected', socketCount)

   socket.on('disconnect', function() {
    // Decrease the socket count on a disconnect, emit
    socketCount--
    io.sockets.emit('users connected', socketCount)
  })

   socket.on('new note', function(data){
    // New note added, push to all sockets and insert into db
    notes.push(data)
    io.sockets.emit('new note', data)
    // Use node's db injection format to filter incoming data
    db.query('INSERT INTO notes (note) VALUES (?)', data.note)
 })

  // Check to see if initial query/notes are set
   if (! isInitNotes) {
    // Initial app start, run db query
    db.query('SELECT * FROM notes')
        .on('result', function(data){
            // Push results onto the notes array
            notes.push(data)
        })
        .on('end', function(){
            // Only emit notes after query has been completed
            socket.emit('initial notes', notes)
        })

       isInitNotes = true
      } else {
    // Initial notes already exist, send out
       socket.emit('initial notes', notes)
     }
    })

我的客户端脚本

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
<script>
 $(document).ready(function(){
 // Connect to our node/websockets server
var socket = io.connect('http://localhost:3000');

// Initial set of notes, loop through and add to list
socket.on('initial notes', function(data){
    var html = ''
    for (var i = 0; i < data.length; i++){
        // We store html as a var then add to DOM after for efficiency
        html += '<li>' + data[i].note + '</li>'
    }
    $('#notes').html(html)
})

// New note emitted, add it to our list of current notes
socket.on('new note', function(data){
    $('#notes').append('<li>' + data.note + '</li>')
})

// New socket connected, display new count on page
socket.on('users connected', function(data){
    $('#usersConnected').html('Users connected: ' + data)
})

// Add a new (random) note, emit to server to let others know
$('.gsub').click(function(){
    var value=$("#txt").val();
  //  var newNote = 'This is a random ' + (Math.floor(Math.random() * 100) + 1)  + ' note'
    socket.emit('new note', {note: value})
  })
  })
  </script>
  <ul id="notes"></ul>
  <div id="usersConnected"></div>
  <div id="newNote">Create a new note</div>
  <input type='text' name='txt' id='txt'><input type='button' value='submit' class='gsub'>

以上两个代码只能在本地机器http://localhost/上正常工作,但是当我尝试连接同一个形式的另一台机器时,我的本地机器http://192.168.21.21/在本地连接在一起,所以不能正常工作,所以请分享您的想法,感谢

1 个答案:

答案 0 :(得分:1)

也许是因为你在客户端代码的几个地方硬编码了localhost。尝试将其更改为使用类似window.location.host的内容。例如,您目前有:

$(document).ready(function(){
    // Connect to our node/websockets server
    var socket = io.connect('http://localhost:3000');
...
});

应该是这样的:

$(document).ready(function(){
    // Connect to our node/websockets server
    var host = window.location.host; // Get the host name here
    var socket = io.connect('http://' + url + ':3000'); //insert the http:// and :3000 here
...
});

这样,当您从另一台计算机访问服务器时,它将连接到http://192.168.21.21:3000而不是它自己的“localhost”。

当您拉入socket.io.js文件时,同样位于HTML的顶部,请确保不要再次从“localhost”中取出它。只需输入:

<script src="/scripts/socketio.js"></script>