User-Triggered Messaging
4:19:50 - 4:36:29 User-Triggered Messaging In this task, users are to create a simple form to receive input from the user. This input is then sent to the server through Socket.io and displayed for all connected clients. Kyle also shows how to emit messages only to the other clients connected and not to the sender.send and receive websocket messages on the client
on the client
<input id="typeit"><input type="button" id="sendbutton" value="send message">
<div id="messages"></div>
to send messages:
document.getElementById("sendbutton").addEventListener("click", function(evt){
var msg = document.getElementById("typeit").value;
if (msg) {
socket.emit("typeit",msg);
document.getElementById("messagebox").innerHTML += msg + "<br>";
document.getElementById("typeit").value = "";
}
});
to receive messages:
socket.on("messages", function(msg){
document.getElementById("messagebox").innerHTML += msg + "<br>";
});
on the server (see note: Making a Socket Connection)
io.on("connection",handleIO);
function handleIO(socket) {
// ... (handle disconnect, etc)
function getmsg(msg) {
io.sockets.emit("broadcast",msg);
}
socket.on("msg",getmsg);
}
io.on("connection",handleIO);
function handleIO(socket) {
// ... (handle disconnect, etc)
socket.on("typeit",function(msg){
socket.broadcast.emit("messages", msg);
});
}
with the socket.broadcast
you will only send to message to everyone else but the client who sent the message. (socket
has been passed to handleIO
as a connection parameter)with
latency is about 50 to 100ms io.broadcast
we would send it to everyone including the sendermost users would perceive less than 100ms as instantaneous