如何仅向特定套接字发送消息.id?

时间:2017-10-03 10:08:18

标签: javascript node.js sockets socket.io

我正在慢慢地将结构设置为一个项目,虽然除了ping源之外我还可以向每个其他用户发出警报,但我仍然需要能够向特定用户发出警报。我认为最好的方法是ping到某个socket.id.任何想法如何做到这一点? socket.broadcast.to(socket.id)似乎在我的设置中不起作用,因为我一直收到错误(无法读取未定义的属性')。

client.js

// BROWSERIFY

//DEPENDENCIES
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");




//Handler for the ping button 

var pingRoom = function () {
  socket.emit('pingAlert');
};

window.pingRoom = pingRoom;


var pingTwo = function () {
  socket.emit('pingAlertTwo');
};

window.pingTwo = pingTwo;



////////////////////////////////////////////////////////


//Intercepts the pingBack event from the server side
socket.on('pingBack', function (data) {
  alert("ALERT");
});

socket.on('pingBackTwo', function (data) {
  socket.broadcast.to(socketid).emit('message', 'for your eyes only');

});
////////////////////////////////////////////////////////


//Peer number counter (incomplete functionality)
p2p.on("peer-num", function (num) {
  console.log("You are peer number " + num);
  $(".peerNum").html("You are connected to " + num + " peers.");
});
////////////////////////////////////////////////////////


//Appends stream to element
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);
});
////////////////////////////////////////////////////////


//Converts file to binary stream and logs progress in the console 
$(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);
  });
});
////////////////////////////////////////////////////////


//Logs users in the user log
socket.on('users_log', function (data) {
  $('#log').append(data + "<br>");
  console.log(data);
});
////////////////////////////////////////////////////////

server.js

//DEPENDENCIES
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");


//Added configuration
app.use(express.static(__dirname));
app.use(express.static("server_scripts"));
app.use(express.static("client_scripts"));
io.use(p2pserver);


//Peer number
var peerNum = 0;
////////////////////////////////////////////////////////

//Connections and disconnections
io.on("connection", function (socket) {

  //Increments the peer number for connected peers
  console.log("Peer " + peerNum + " connected");
  io.emit("peer-num", peerNum);
  peerNum++;
  ////////////////////////////////////////////////////////


  //Streamer
  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);
    });

  });
  ////////////////////////////////////////////////////////


  //Holds the socket.id of connections
  ID = socket.id;
  ////////////////////////////////////////////////////////


  //Emits connection status to user end (User ID log)
  io.sockets.emit('users_log', "client id - " + ID + " connected");
  io.sockets.emit('users_online', ID);
  ////////////////////////////////////////////////////////


  //Server side logging of connections
  console.log('client id - ' + ID + ' connected.');
  ////////////////////////////////////////////////////////


  //Alert listener and response
  socket.on('pingAlert', function () {
    console.log('Ping');
    io.sockets.emit('pingBack');
  });


  socket.on('pingAlertTwo', function () {
    console.log('PingTwo');
    io.sockets.emit('pingBackTwo');
  });
  ////////////////////////////////////////////////////////


  //Handles disconnections
  socket.on('disconnect', function () {


    //Emits disconnection to user end (User ID log)
    io.sockets.emit('users_log', "client id - " + ID + " disconnected");
    //Decreases peer counter on disconnect
    peerNum--;
    ////////////////////////////////////////////////////////


    //Server side logging of disconnections
    console.log('client id - ' + ID + ' disconnected.')
    io.sockets.emit('users_offline', ID);
    //NOTE: Features need to be added here
    ////////////////////////////////////////////////////////
  })
});


//Listen on 
server.listen(8000, function () {
  console.log("Listening on 8000")
});

2 个答案:

答案 0 :(得分:2)

io.sockets.connected[ID].emit('ping',data);

ID是socketId,数据是您希望随事件发送的有效负载。

答案 1 :(得分:0)

当您编写socket.function()时会为所有用户发出事件,但如果您编写socket.emit(),则会为该特定套接字发出事件。

如果您希望向特定用户发送一些消息,请使用function.php功能。