Junior — Middle
Can you explain what a WebSocket protocol is and how it is used for real-time data exchange?
sobes.tech AI
Answer from AI
WebSocket is a communication protocol that provides a bidirectional, persistent communication channel between the client and server over a single TCP connection. Unlike traditional HTTP, where the client makes a request and receives a response, WebSocket allows the server to send data to the client at any time without repeated requests.
It is used for real-time data exchange applications, such as:
- Chats
- Online games
- Financial trading platforms
- Notification systems
Example of usage 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);
};
Thus, WebSocket allows maintaining a constant connection and quickly exchanging messages between the client and server.