如何使用 socket.io 发送消息
how to send messages using socket.io
我想使用 socket.io 和 node 作为我的"推送通知功能"的层,所以我同时运行 apache 和 node。
我的服务器(节点)上有以下代码
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
这应该可以正常工作,只需确保在您的索引中.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!!!");
});
});
对于索引.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。
相关文章:
- 通过node.js和socket.io在两个用户之间发送消息
- Socket.IO 客户端库提供“欢迎来到 socket.io”消息
- io.sockets.mit未向服务器发送消息
- 为什么我的消息没有用这个处理程序发送到Socket.io房间
- 在socket.io中从客户端发送广播消息
- 服务器到服务器套接字IO消息
- 发送消息时,Socket.io聊天重新加载页面
- Socket.IO聊天不发送和/或接收消息
- 如何确保客户端已收到通过socket.io发送的消息
- socket.io 客户端,不会向服务器发出消息
- Socket.io,给自己发消息
- socket.io 不记录控制台消息
- 向聊天室发送消息 socket.io 节点.js
- Socket.io 向某些套接字(体系结构)发出消息
- 向节点.js和 socket.io 中的单个套接字发送消息
- 用于 Block.io API 的 Websockets 给出错误消息
- Socket.io 无法连续发送两条消息
- 安装程序 prerender.io 仅从 PhantomJS 输出错误消息
- 为服务器中的每个客户端累积消息 Socket.io
- 向Socket发送消息.IO通过get请求