Junior — Middle
Can you explain what web sockets are and how they work in the context of web development?
sobes.tech AI
Answer from AI
WebSockets are a protocol that provides a two-way persistent connection between a client (e.g., a browser) and a server. Unlike traditional HTTP, where the client sends a request and receives a response, WebSockets allow the server to send data to the client at any time without repeated requests.
Here's how they work:
- The client initiates a connection via HTTP with the header
Upgrade: websocket. - If the server supports WebSockets, the connection is 'upgraded' from HTTP to WebSocket.
- After establishing the connection, the client and server can exchange messages in real time.
An example use case is chat, online games, or updating data on a page without reloading.
Here's an example in JavaScript for connecting to a WebSocket:
const socket = new WebSocket('wss://example.com/socket');
socket.onopen = () => {
console.log('Connection established');
socket.send('Hello server!');
};
socket.onmessage = event => {
console.log('Received message:', event.data);
};