【发布时间】:2016-10-07 00:38:28
【问题描述】:
我正在尝试用 WebSockets 连接一个小游戏。我正在使用 socket.io、socket.io-p2p 和 socket.io-p2p-server。我希望用户自动与任何没有合作伙伴的已连接玩家配对。我希望用户只能成对连接。
到目前为止,只需按照文档进行操作,我就只能使用 socket.io 让客户端进行连接。当我尝试使用 socket.io-p2p 和 socket.io-p2p-server 时,有时我可以让用户连接,有时我会在屏幕上收到错误消息,例如
“socket 上缺少错误处理程序。
TypeError:无法读取未定义的属性“发射”
有人在 repo 上为这个问题打开了一个 issue,没有得到回应,也没有得到回应
https://github.com/tomcartwrightuk/socket.io-p2p-server/issues/5
我不知道 socket.io-p2p-server 是否坏了,或者我只是遗漏了一些东西。还有更多的 socket.io-p2p-server 自 3 月以来没有太多接触。
所以我的主要问题是:
socket.io-p2p-server 还活着吗?
我可以为这些抽象使用更好的实现吗?
是否值得编写自己的逻辑而不是使用 socket.io-p2p-server?
客户端代码
import P2P from 'socket.io-p2p'
import io from 'socket.io-client'
const socket = io()
const p2pSocket = new P2P(socket, null, function () {
console.log("my id is: " + p2pSocket.peerId)
})
p2pSocket.on('peer-msg', function (data) {
console.log(data)
})
服务器端代码
var http = require('http')
var httpServer = http.createServer(requestHandler)
var fs = require('fs')
var io = require('socket.io')(httpServer)
var p2pServerModule = require('socket.io-p2p-server')
var p2p = p2pServerModule.Server
var connectedUsers = p2pServerModule.clients
io.use(p2p)
httpServer.listen(8000, 'localhost');
function serveUpFile(req, res, path) {
fs.readFile(path.toString(), function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200)
res.end(data)
})
}
function requestHandler (req, res) {
if (req.url === '/static/bundle.js') {
serveUpFile(req, res, './static/bundle.js')
} else {
serveUpFile(req, res, './index.html')
}
}
io.on('connection', function (client) {
console.log('client connected to the server')
client.on('peer-msg', function (data) {
console.log('Message from peer %s', data)
})
client.on('disconnect', function () {
console.log('client disconnected from the server')
})
})
【问题讨论】:
标签: node.js sockets socket.io webrtc p2p