shm*_*mow 47 javascript html5 websocket node.js socket.io
我对node.js和它的插件都比较新,所以这可能是一个初学者问题.
我试图在Web服务器上获得一个简单的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>
Run Code Online (Sandbox Code Playgroud)
服务器端
// 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 + '/');
Run Code Online (Sandbox Code Playgroud)
启动服务器工作正常并在我的浏览器中运行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
Run Code Online (Sandbox Code Playgroud)
我整天都在这里.有帮助吗?
Lio*_*hen 40
您是否尝试过不是从相对URL加载socket.io脚本?
你正在使用:
<script src="socket.io/socket.io.js"></script>
Run Code Online (Sandbox Code Playgroud)
和:
socket.connect('http://127.0.0.1:8080');
Run Code Online (Sandbox Code Playgroud)
你应该试试:
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
Run Code Online (Sandbox Code Playgroud)
和:
socket.connect('http://localhost:8080');
Run Code Online (Sandbox Code Playgroud)
切换localhost:8080适合您当前设置的任何内容.
此外,根据您的设置,从其他域(同源策略)加载客户端页面时,您可能会遇到一些与服务器通信的问题.这可以通过不同的方式克服(在这个答案的范围之外,google/SO它).
小智 14
您需要确保在链接到socket.io之前添加正斜杠:
<script src="/socket.io/socket.io.js"></script>
Run Code Online (Sandbox Code Playgroud)
然后在视图/控制器中执行:
var socket = io.connect()
Run Code Online (Sandbox Code Playgroud)
那应该可以解决你的问题.
| 归档时间: |
|
| 查看次数: |
133689 次 |
| 最近记录: |