Socket
Socket
Basic Usage
1. Installation
To get started, you need to install the Socket.IO server and client libraries.
On the server:
npm install socket.io
On the client:
<script src="/socket.io/socket.io.js"></script>
socket.on('disconnect', () => {
console.log('user disconnected');
});
server.listen(3000, () => {
console.log('listening on *:3000');
});
Client-Side Code
The client code can connect to the server and send/receive messages:
<!DOCTYPE html>
<html>
<head>
<title>Socket.IO Chat</title>
</head>
<body>
<input id="messageInput" type="text" placeholder="Type a
message...">
<button onclick="sendMessage()">Send</button>
<ul id="messages"></ul>
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io();
function sendMessage() {
const msg = document.getElementById('messageInput').value;
socket.emit('chat message', msg);
document.getElementById('messageInput').value = '';
}
</script>
</body>
</html>
Concepts
Namespaces: Useful for splitting up the logic in different parts of
an application. For example, /admin could be a separate namespace
for administrative functionality.
Rooms: Allow clients to join specific channels. Messages can be
broadcast to all clients in a room, rather than all connected clients.