Я возился с Socket IO и успешно подключил двух клиентов к одной комнате. Теперь я хочу получить информацию о пользователях от обоих подключенных пользователей. Легко получить sh данные от второго пользователя, но мне трудно обернуться, как я должен получить данные от второго пользователя, показывающие их первому пользователю.
Вот фрагмент кода сервера:
let rooms = [];
let numUsers = 0;
io.on("connection", socket => {
let addedUser = false;
socket.room = "Public";
socket.join(socket.room);
const totalUsers = io.engine.clientsCount;
socket.emit("getCount", {
totalUsers: totalUsers
});
// Default username
socket.username = "Stranger";
socket.on("addUser", () => {
if (addedUser) return;
++numUsers;
addedUser = true;
socket.broadcast.emit("usersCounter", {
numUsers: numUsers
});
});
socket.on("searchStranger", data => {
rooms.push(data);
socket.broadcast.emit("rooms", rooms);
socket.leave(socket.room);
socket.room = data.room;
socket.join(socket.room);
});
socket.on("foundStranger", data => {
rooms.push(data);
socket.leave(socket.room);
socket.room = data.room;
socket.join(socket.room);
socket.broadcast.emit("rooms", rooms);
rooms = [];
// Clear rooms
socket.broadcast.emit("rooms", rooms);
socket.broadcast.to(socket.room).emit("foundStranger", {
rooms: rooms,
room: socket.room,
// Here the second connected user push the username, but how can I pull the username into the first user?
// I feel like this is not the correct way to do it.
username: socket.username
});
});
socket.on("leaveRoom", username => {
socket.leave(socket.room);
socket.room = "Public";
socket.join(socket.room);
});
socket.on("disconnect", function () {
if (addedUser) {
--numUsers;
}
socket.broadcast.emit("usersCounter", {
numUsers: numUsers
});
});
});
А вот фрагмент клиента JS:
let room = "Public";
let rooms = [];
let userName = "Stranger";
socket.on("connect", () => {
socket.on("getCount", data => {
$("#users-counter").text("Users online: " + data.totalUsers);
});
socket.emit("addUser");
$chatMsgContainer.append($("<li>").text("You are currently in the Public chatroom. Click next to match a random stranger!"));
});
findStrangerBtn.on("click", () => {
const userNickInput = $("#userNick");
if (userNickInput.val() != "") {
userName = userNickInput.val();
}
$("#localNick").append("Your nick: " + userName);
findNewStranger(userName, userAge, userGender);
});
function findNewStranger(userName, userAge, userGender) {
socket.emit("userInfo", { username: userName });
// If a room exist
if (rooms.length > 0) {
$.each(rooms, (index, value) => {
socket.emit("foundStranger", {
room: value.room,
username: userName
});
$chatMsgContainer.append($("<li>").text("You matched with a new stranger."));
rooms = [];
return false;
});
// If a room doesn't exist we create one
} else {
$chatMsgContainer.append($("<li>").text("Searching for a new stranger..."));
// Create new room
room = makeId();
socket.emit("searchStranger", {
room: room,
username: userName
});
rooms.push({
room: room
});
}
}
socket.on("foundStranger", data => {
$chatMsgContainer.append($("<li>").text("You matched with a new stranger."));
$("#remoteNick").text("Stranger nick: " + data.username);
rooms = [];
room = data.room;
});
socket.on("rooms", data => {
rooms = data;
});
socket.on("usersCounter", (data) => {
$("#users-counter").text("Users online: " + data.numUsers);
});
function makeId() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 5; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}