WebSocket: WebSocket is a protocol that provides a full-duplex communication channel over a single TCP connection. It allows for real-time communication between the client and the server. Here's an example of how to create a WebSocket server using the ws package:
javascript
const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 8080 });
server.on('connection', (socket) => {
console.log('Client connected');
socket.on('message', (message) => {
console.log(`Received message: ${message}`);
// Echo the message back to the client
socket.send(`You said: ${message}`);
});
socket.on('close', () => {
console.log('Client disconnected');
});
});
In this example, we create a WebSocket server using the ws package and listen for client connections. We handle incoming messages and echo them back to the client. We also handle client disconnections.
No comments:
Post a Comment