jcayzac
jcayzac7mo ago

Does fetch() support upgrading the connection to a websocket?

What happens when fetch() gets the response
HTTP/1.1 101 Switching Protocols
connection: upgrade
upgrade: websocket
HTTP/1.1 101 Switching Protocols
connection: upgrade
upgrade: websocket
…? How to get the WebSocket object from there?
2 Replies
Deno AI Helper
Deno AI Helper7mo ago
I wasn't able to find the answer to your question in the official Deno documentation. However, based on the general behavior of the fetch() API, it is not designed to handle protocol upgrades like upgrading an HTTP connection to a WebSocket directly within its response handling. The fetch() API is generally used for making HTTP requests and handling HTTP responses. When a server responds with a 101 Switching Protocols status, it indicates that the server is switching protocols as requested by the client, typically in response to a WebSocket handshake request. In standard browser environments and possibly in Deno, to establish a WebSocket connection, you would typically use the WebSocket constructor directly, rather than using fetch(). Here's an example of how you might initiate a WebSocket connection:
const socket = new WebSocket('ws://example.com/');
socket.onopen = function(event) {
console.log('WebSocket is open now.');
};
socket.onmessage = function(event) {
console.log('Received data from websocket: ', event.data);
};
socket.onerror = function(event) {
console.error('WebSocket error observed:', event);
};
const socket = new WebSocket('ws://example.com/');
socket.onopen = function(event) {
console.log('WebSocket is open now.');
};
socket.onmessage = function(event) {
console.log('Received data from websocket: ', event.data);
};
socket.onerror = function(event) {
console.error('WebSocket error observed:', event);
};
This advice is not based on the Deno documentation, so please double-check the accuracy of this advice and consult the Deno documentation or community for more specific guidance on handling WebSockets in Deno.
crowlKats
crowlKats7mo ago
that is sadly not possible