0
我設法通過讓控制檯爲每個新連接的對等體打印出「您是對等體編號n」來獲得我的控制檯日誌中連接的對等體的數量。 有沒有辦法添加每個連接的同行的ID? 我是相對較新的socket.io,我似乎無法找到辦法做到這一點。如何獲取連接對等的ID?
這是我server.js文件:
var app = require("express")();
var express = require("express");
var server = require("http").Server(app);
var p2pserver = require("socket.io-p2p-server").Server;
var io = require("socket.io")(server);
var ss = require("socket.io-stream");
var path = require("path");
app.use(express.static(__dirname));
io.use(p2pserver);
var peerNum = 0;
io.on("connection", function(socket) {
console.log("Peer " + peerNum + " connected");
io.emit("peer-num", peerNum);
peerNum++;
ss(socket).on("file", function(stream, data) {
var filename = path.basename(data.name);
var parts = [];
stream.on("data", function(data) {
parts.push(data);
});
stream.on("end", function() {
socket.broadcast.emit("file", parts);
});
});
});
server.listen(8080, function() {
console.log("Listening on 8080")
});
這是我client.js文件:
// Browserified
var P2P = require("socket.io-p2p");
var io = require("socket.io-client");
var ss = require("socket.io-stream");
var socket = io();
var opts = {autoUpgrade: true, peerOpts: {numClients: 10}};
var p2p = new P2P(socket, opts);
var $ = require("jquery");
p2p.on("peer-num", function(num) {
console.log("You are peer number " + num);
$(".peerNum").html("Number " + num);
});
p2p.on("file", function(stream) {
console.log(stream);
var img = document.createElement("img");
img.src = (window.URL || window.webkitURL).createObjectURL(new Blob(stream));
document.getElementById("receivedImages").appendChild(img);
});
$(function() {
$("#file").change(function(e) {
ss.forceBase64 = true;
var file = e.target.files[0];
var stream = ss.createStream();
ss(socket).emit("file", stream, {size: file.size,name:file.name});
var blobStream = ss.createBlobReadStream(file);
var size = 0;
blobStream.on("data", function(chunk) {
size += chunk.length;
console.log(Math.floor(size/file.size * 100) + "%");
});
blobStream.pipe(stream);
});
});
這樣做。 謝謝。 –