Junior — Middle
How is data exchange implemented via WebSocket on the client side in web applications?
sobes.tech AI
Answer from AI
Data exchange via WebSocket on the client side in web applications is implemented using the JavaScript WebSocket API, which allows establishing a persistent bidirectional connection with the server.
Main steps:
- Creating a WebSocket object with the server URL:
const socket = new WebSocket('ws://example.com/socket');
- Handling events:
onopen— connection establishedonmessage— message received from the serveronerror— connection erroronclose— connection closed
- Sending messages to the server:
socket.send('Hello, server!');
Example:
const socket = new WebSocket('ws://localhost:8080/ws');
socket.onopen = () => {
console.log('Connection opened');
socket.send('Hello from client');
};
socket.onmessage = (event) => {
console.log('Message received:', event.data);
};
socket.onerror = (error) => {
console.error('Error:', error);
};
socket.onclose = () => {
console.log('Connection closed');
};
Thus, WebSocket provides efficient real-time data exchange between client and server without the need for constant HTTP requests.