Middle
What is WebSocket? What is it used for?
sobes.tech AI
Answer from AI
WebSocket is a communication protocol that provides full-duplex interaction between the client and server over a single persistent TCP connection. Unlike traditional HTTP, where the client initiates each request, WebSocket allows the server to send data to the client at any time without an additional request.
It is used for applications that require real-time data exchange, such as:
- Chat applications
- Online games
- Financial trading platforms
- Monitoring systems
Example of creating a WebSocket client in JavaScript:
const socket = new WebSocket('wss://example.com/socket');
socket.onopen = () => {
socket.send('Hello server!');
};
socket.onmessage = event => {
console.log('Received message:', event.data);
};