what is websocket
its just a communicstion protocal like http,ftp,smt
http till now used for api
http vs websocket
http - one way : client request and server response to that request . note server can’t send data according to its mood it can send data(resposne) only when there request from the client
websocket - a connection is establish between client and server
it follows duplex communication i.e. even if client is not resquesting anything and connection is still established then server can send data (response) on its own no need of request from client
what is io
io represent the circuit and socket represent the client
and this circuit can be coresponding to the server so server has a circuit
io and socket diagram : in the screenshot
emit and on
emit - Used to send an event with some data and Can be used on both server and client. sending the data
eg - socket.emit(“eventName”, data);
socket.emit(“hello”,”namaste duniya”)
note: event name should be in “ “
on - Used to listen for an event. and Can be used on both server and client. receiving the data
eg - socket.on(“eventName”, callback function);
socket.on(“hello”,(msg)=>{
console.log(the message send by emit is ${msg});
})
Server listens with .on() and runs a callback
make sure the event name is same for both of them and callback function tells what task to perform when the event is triggered through emit
the data send by emit is revecied as parameter of callback function which can be later manipulated inside the function to perform task needed
when written io.emit or io.on then means we are triggering event or sending message to all the socket in the circuit(io)
whereas if you want to trigger event / send message to particular to one socket then socket.emit / socket.on
broadcast , to , join
broadcast is the method used to send data to everyone except the socket that triggered the event
therefore - Broadcasting means sending a message to all connected clients except the one who sent it.
socket.broadcast.emit(“chatMessage”, msg);
.on() and broadcast are not used together.
.on(event, callback) → listens for an event.
.broadcast.emit(event, data) → sends an event to everyone except the sender.
They are used on opposite sides:
One socket emit or broadcast.emit → sends.
Other sockets use on → listen.