How to Use On Client Side
1. Add this script to your html where you need to connect using socket
<script
src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>
2. Connect to Socket ServerUpdated
const socket = io("https://socket.emdrremote.com", { transports:
["websocket"] });
3. Register a client with its info
socket.emit("store-client-info", { uid: "Client1" }); //
uid is the Client's unique id which is used to identify
the client on Recipient's side
4. Send data to a recipient Updated
socket.emit("send-data", {
recipientId: "Client2",
// recipientId is uid of the recipient who is
supposed to receive this data.
command: "send-coordinates",
// command tells the recipient what is the data
for.
data: { x: 123, y: 345 }
// data, whose type can be any, will be consumed by
the recipient due to command
});
5. Receive data from a sender Updated
socket.on("receive-data", (payload) => {
const { senderId,
command, data } = payload; // senderId is
uid of the sender.
// process command with data something like this
// if (command === "send-coordinates") {
// const { x, y } = data;
// //process x & y
// }
});
6. How to handle Disconnect Event Updated
let intentionalDisconnection = false; // a variable used to determine if disconnection is intentional or accidental on disconnect event handler
socket.on("intentional-disconnect", (data) => { // intentional disconnection triggered by server due to a second connection
intentionalDisconnection = true;
const { message } = data;
//console.log(message);
});
socket.on("disconnect", () => { // an event handler triggered when disconnected with server anyway, * if an intentional disconnection, it will be triggered as soon as intentional-disconnect event is triggered
if (intentionalDisconnection) {
// this is an intentional disconnection;
} else {
// this is an accidental disconnection;
}
intentionalDisconnection = false; //initialize the variable
});
How to Limit Frequency of Emitting Data on Frontend
let oldX = -1, oldY = -1, newX = -1, newY = -1;
let recipientId = '12345';
some_function(xx, yy) { // detect new coordinate of mouse and update
newX, newY
newX = xx; newY = yy;
}
const emitData = () => { // a function that sends data
if(oldX != newX || oldY != newY) {
socket.emit("send-coordinates", {
recipientId: recipientId,
x: newX,
y: newY
});
oldX = newX;
oldY = newY;
}
}
setInterval(emitData, 100); // runs the function emitData every 100
miliseconds so data will be emitted every 100 milisecs which means 10
times per second.