我对node.js及其插件是相对较新的,因此这可能是一个初学者的问题。
我试图在网络服务器上获得一个简单的HTML页面,该页面连接到另一个使用websocket.io运行node.js的服务器。
我的代码如下所示:
客户
<script src="socket.io/socket.io.js"></script>
<script>
// Create SocketIO instance, connect
var socket = new io.Socket();
socket.connect('http://127.0.0.1:8080');
// Add a connect listener
socket.on('connect',function() {
console.log('Client has connected to the server!');
});
// Add a connect listener
socket.on('message',function(data) {
console.log('Received a message from the server!',data);
});
// Add a disconnect listener
socket.on('disconnect',function() {
console.log('The client has disconnected!');
});
// Sends a message to the server via sockets
function sendMessageToServer(message) {
socket.send(message);
};
</script>
服务器端
// Require HTTP module (to start server) and Socket.IO
var http = require('http');
var io = require('socket.io');
var port = 8080;
// Start the server at port 8080
var server = http.createServer(function(req, res){
// Send HTML headers and message
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 + '/');
启动服务器可以正常工作,并且在我的浏览器中运行http:// localhost:8080也可以,并按预期返回“ Hello Socket Lover”。但是我想让其他页面与套接字对话,而不是从node.js运行页面。
但是,当我运行它时,没有任何反应,Chrome控制台返回:
Failed to load resource http://undefined/socket.io/1/?t=1333119551736
Failed to load resource http://undefined/socket.io/1/?t=1333119551735
我整天都在这。有什么帮助吗?
您是否尝试过不从相对URL加载socket.io脚本?
您正在使用:
<script src="socket.io/socket.io.js"></script>
和:
socket.connect('http://127.0.0.1:8080');
你应该试试:
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
和:
socket.connect('http://localhost:8080');
切换localhost:8080
任何适合您当前设置的方式。
另外,根据您的设置,从其他域加载客户端页面时,与服务器通信时可能会遇到一些问题(同源策略)。这可以通过不同的方式来克服(在此答案的范围之外,google / so it)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句