连接到第三方socket.io服务器

时间:2017-10-22 17:17:14

标签: javascript socket.io

我正在创建一个socket.io服务器,如下所示:

var http = require('http');
var io = require('socket.io');
var port = 8080;

var server = http.createServer(function(req, res){ 
    res.writeHead(200,{ 'Content-Type': 'text/html' }); 
    res.end('<h1>Hello Socket Lover!</h1>');
});

server.listen(port);

// Create a Socket.IO instance, passing it our server
var socket = io.listen(server);
// Add a connect listener
socket.on('connection', function(client){ 
    console.log('Connection to client established');

    // Success!  Now listen to messages to be received
    client.on('message',function(event){ 
        console.log('Received message from client!',event);
    });

    client.on('disconnect',function(){
        clearInterval(interval);
        console.log('Server has disconnected');
    });
});

console.log('Server running at http://127.0.0.1:' + port + '/');

服务器工作正常并启动,但是当我通过这样的js连接时:

$(function(){

var socket = io();
socket.connect('http://localhost:8080');

});

它没有连接,我在开发工具控制台中得到它。

polling-xhr.js:264 GET http://file/socket.io/?EIO=3&transport=polling&t=Lz53lhL net::ERR_NAME_NOT_RESOLVED

我正在加载socket.io.js:

<script src="http://127.0.0.1:8080/socket.io/socket.io.js"></script>

1 个答案:

答案 0 :(得分:0)

更改

$(function(){

var socket = io();
socket.connect('http://localhost:8080');

});

$(function(){

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

});

您需要将套接字服务器的url传递给io函数