我正在使用 node.js 和 express 编写一个网络应用程序来提供实时 aprs通过 ZeroMQ 和 socket.io 流式传输给每个用户。
概念是:node.js 应用程序通过订阅 ZeroMQ 发布者将完整的 aprs 流发送给它。当用户访问网页(全屏 map )时,会建立一个 socket.io session 并将 map 当前可见区域的边界发送回服务器。然后,服务器可以确定完整提要的范围,以仅将 map 上的新地点发送给用户。
它的大部分运行良好,但当不止一个人加载该站点时它就会中断。当前查看的 map 范围变为全局范围,如果您缩放/平移一张 map ,它将开始向两个浏览器显示新位置上的地点。
我需要每个 socket.io session 保留自己的范围,并且只从其唯一的范围 map 边界接收数据,并且对每个访问者都是唯一的。我试过在 socket.io 连接中嵌套 zmqsocket.on "message", (data) ->
回调,但它仍然产生相同的结果(即使在适当的范围内声明了 mapbounds 变量回调。)
可在此处找到该应用程序的完整源代码:https://github.com/gmcintire/aprs.bz
如果你想在本地测试应用程序,你应该能够克隆我的 repo,运行 npm install
,然后 coffee app.coffee
开始。请注意,它将开始从我的 ZeroMQ 服务器流式传输完整的 APRS 提要,这可能是 ~100KBytes/sec。
app.咖啡
express = require("express")
routes = require("./routes")
geolib = require("geolib")
zmq = require("zmq")
zmqsocket = zmq.socket("sub")
zmqsocket.connect "tcp://stream.aprs.bz:12777"
zmqsocket.subscribe ""
app = module.exports = express.createServer()
io = require("socket.io").listen(app)
mapbounds = ""
io.sockets.on "connection", (socket) ->
#console.log socket
socket.on "mapmove", (mapcoords) ->
console.log mapbounds
mapbounds = mapcoords
zmqsocket.on "message", (data) ->
packet = JSON.parse(data)
#console.log packet
if packet.latitude? and packet.longitude? and (mapbounds != "")
insideMap = geolib.isPointInside
latitude: packet.latitude
longitude: packet.longitude
, [
latitude: mapbounds._northEast.lat
longitude: mapbounds._southWest.lng
,
latitude: mapbounds._northEast.lat
longitude: mapbounds._northEast.lng
,
latitude: mapbounds._southWest.lat
longitude: mapbounds._northEast.lng
,
latitude: mapbounds._southWest.lat
longitude: mapbounds._southWest.lng
]
if insideMap
console.log "\n--------------------------------------------------------\n"
io.sockets.emit "packet", packet
console.log packet
app.configure ->
app.set "views", __dirname + "/views"
app.set "view engine", "jade"
app.use express.bodyParser()
app.use express.methodOverride()
app.use app.router
app.use express.static(__dirname + "/public")
app.configure "development", ->
app.use express.errorHandler(
dumpExceptions: true
showStack: true
)
app.configure "production", ->
app.use express.errorHandler()
app.get "/", routes.index
if app.settings.env == "development"
app.listen 3000
else
app.listen 80
console.log "Express server listening on port %d in %s mode", app.address().port, app.settings.env
最佳答案
我也不是 CS 或 ZMQ 专家,但听起来您正在向太多客户端广播数据。 io.sockets.emit
将事件发送到所有连接的套接字。如果只想将数据发送到 1 个套接字,则应使用 socket.emit
,其中 socket
已设置为单个套接字对象。
关于带有 ZeroMQ + Socket.io + 每个客户端范围的 Node.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10064474/