[英]how to send messages using socket.io
我想使用 socket.io 和節點作為我的“推送通知功能”的層,所以我同時運行 apache 和節點。
我的服務器(節點)上有以下代碼
var app = require('http').createServer(handler)
, io = require('C:/path/to/file/socket.io').listen(app)
, fs = require('fs');
app.listen(8080);
function handler(req, res) {
console.log(req);
fs.readFile('C:/path/to/file/index.html',
function (err, data) {
if (err) {
console.log(err);
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
socket.on('my event', function (msg) {
console.log("DATA!!!");
});
});
然后該頁面由 apache 從沒有 8080 端口的本地主機提供服務
在客戶端我有以下代碼:
var socket = io.connect('http://localhost:8080');
單擊按鈕時:
socket.emit('my event', {data:"some data"});
我在節點控制台上什么也看不到……這是為什么? 跨域問題?
更新:它在 safari 5.1.5 甚至 IE 9 上工作得很好,但在 chrome(18.0.1025.151) 或 firefox (11.0) 上卻不行……我錯過了什么?
這是節點日志:
info - socket.io started
debug - served static content /socket.io.js
debug - client authorized
info - handshake authorized 4944162402088095824
debug - setting request GET /socket.io/1/websocket/4944162402088095824
debug - set heartbeat interval for client 4944162402088095824
debug - client authorized for
debug - websocket writing 1::
debug - setting request GET /socket.io/1/xhr-polling/4944162402088095824?t=13
33977095905
debug - setting poll timeout
debug - discarding transport
debug - cleared heartbeat interval for client 4944162402088095824
那應該可以正常工作,只需確保在您的 index.html 中您有:
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
此外,由於您通過 Apache 為您的頁面提供服務,因此您實際上不需要節點文件中的處理程序和 http 服務器。 這應該工作得很好:
var io = require('socket.io').listen(8080);
io.sockets.on('connection', function (socket) {
socket.on('my event', function (msg) {
console.log("DATA!!!");
});
});
對於 index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello World!</title>
<meta charset="utf-8">
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var socket = io.connect('http://localhost:8080');
$("#button").click(function() {
socket.emit('my event' ,"Hello World!");
})
})
</script>
</head>
<body>
<button type="button" id='button'>Send Message</button>
</body>
</html>
編輯:這適用於 Firefox 和 Chrome。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.