tiger1
July 19, 2021, 5:53pm
1
Hi, can anyone help me fix my websocket relay code?
Here it is:
const WORKER_URL = 'https://wss-relay.tigercox.workers.dev';
const WSS_CAM1 = 'wss://echo.websocket.org';
const WSS_CAM2 = 'wss://echo.websocket.org';
/**
* HELPERS: Receives a HTTP request and replies with a response.
* @param {WebSocket} websocket
* @returns {Promise<void>}
*/
async function handleSession(websocket) {
try {
websocket.accept();
websocket.addEventListener("message", async message => {
console.log(message);
});
websocket.addEventListener("close", async evt => {
// Handle when a client closes the WebSocket connection
console.log(evt);
});
} catch (handleSessionError) {
console.log('Handle Session error', handleSessionError);
}
}
/* >>> REQUEST HANDLER <<< */
/**
* Receives a HTTP request and replies with a response.
* @param {Request} request
* @returns {Promise<Response>}
*/
async function handleRequest(request) {
const {
pathname
} = new URL(request.url);
const upgradeHeader = request.headers.get("Upgrade");
if (upgradeHeader !== "websocket") {
return new Response("Expected websocket", {
status: 400
});
}
// Need to be handled client socket from worker - TO-Do
const [client, server] = Object.values(new WebSocketPair());
await handleSession(server);
switch (pathname) {
case '/':
{
return new Response('Anyone can access the homepage.');
}
case '/cam1':
{
return new Response(null, {
status: 101,
webSocket: client
});
}
case '/cam2':
{
return new Response(null, {
status: 101,
webSocket: client
});
}
}
return new Response("Not Found", {
status: 404
});
}
addEventListener('fetch', event => {
event.respondWith(
handleRequest(event.request)
.then(response => {
response.headers.set('Access-Control-Allow-Origin', '*')
return response
})
.catch(err => {
console.log('Error on fetch event', err)
const message = err.reason || err.stack || 'Unknown Error'
return new Response(message, {
status: err.status || 500,
statusText: err.statusText || null,
headers: {
'Content-Type': 'text/plain;charset=UTF-8',
// Disables caching by default.
'Cache-Control': 'no-store',
// Returns the "Content-Length" header for HTTP HEAD requests.
'Content-Length': message.length,
},
})
}), )
});
matteo
July 19, 2021, 7:59pm
3
Can you please post this as a code block and format it? It becomes pretty unreadable.
It’s ```
before and after the code to make a code block.
matteo
July 19, 2021, 9:17pm
5
That solved nothing… It’s only three backticks before and after.
1 Like
tiger1
July 19, 2021, 9:18pm
6
its not working
const WORKER_URL = 'https://wss-relay.tigercox.workers.dev';
const WSS_CAM1 = 'wss://echo.websocket.org';
const WSS_CAM2 = 'wss://echo.websocket.org';
/**
* HELPERS: Receives a HTTP request and replies with a response.
* @param {WebSocket} websocket
* @returns {Promise<void>}
*/
async function handleSession(websocket) {
try {
websocket.accept();
websocket.addEventListener("message", async message => {
console.log(message);
});
websocket.addEventListener("close", async evt => {
// Handle when a client closes the WebSocket connection
console.log(evt);
});
} catch (handleSessionError) {
console.log('Handle Session error', handleSessionError);
}
}
/* >>> REQUEST HANDLER <<< */
/**
* Receives a HTTP request and replies with a response.
* @param {Request} request
* @returns {Promise<Response>}
*/
async function handleRequest(request) {
const {
pathname
} = new URL(request.url);
const upgradeHeader = request.headers.get("Upgrade");
if (upgradeHeader !== "websocket") {
return new Response("Expected websocket", {
status: 400
});
}
// Need to be handled client socket from worker - TO-Do
const [client, server] = Object.values(new WebSocketPair());
await handleSession(server);
switch (pathname) {
case '/':
{
return new Response('Anyone can access the homepage.');
}
case '/cam1':
{
return new Response(null, {
status: 101,
webSocket: client
});
}
case '/cam2':
{
return new Response(null, {
status: 101,
webSocket: client
});
}
}
return new Response("Not Found", {
status: 404
});
}
addEventListener('fetch', event => {
event.respondWith(
handleRequest(event.request)
.then(response => {
response.headers.set('Access-Control-Allow-Origin', '*')
return response
})
.catch(err => {
console.log('Error on fetch event', err)
const message = err.reason || err.stack || 'Unknown Error'
return new Response(message, {
status: err.status || 500,
statusText: err.statusText || null,
headers: {
'Content-Type': 'text/plain;charset=UTF-8',
// Disables caching by default.
'Cache-Control': 'no-store',
// Returns the "Content-Length" header for HTTP HEAD requests.
'Content-Length': message.length,
},
})
}), )
});
tiger1
July 19, 2021, 9:19pm
8
Yep thanks, so my const WSS_CAM1 is not defined and I’m not sure how to place that. Eg where that response should go
matteo
July 19, 2021, 9:21pm
9
Do you have something that’s not working with a feature in Cloudflare or are you trying to ask us to help you write code?
1 Like
tiger1
July 19, 2021, 9:23pm
10
Well given that I advocate cloudflare to anyone who asks, and pay them monthly, and Im helping test the relatively new worker websockets feature. I just need some minor pointers… this could be a big use case for cf workers in the future. I just need a little advice, thank you for your time
matteo
July 19, 2021, 9:29pm
11
As I am not paid, nor employed by Cloudflare that isn’t really convincing me…
Also, not even knowing what you are doing and as Cloudflare’s policy is, we don’t normally write code for others, unless it’s to fix an issue with an actual feature. Websocket support on Workers does work well, that I know.
2 Likes
tiger1
July 19, 2021, 9:32pm
12
Fair enough, thats ok. Im glad it works well, shame I wont find out because my skills are too low to finish the code. I just need this to work so we can get our community harbour webcams (jsmpeg) back online. Do you know anyone with cf skills I could pay to do this?
matteo
July 19, 2021, 9:33pm
13
It doesn’t require CF skills, it’s simply a matter of a good web developer that has experience with Service Workers.
tiger1
July 19, 2021, 9:36pm
14
Do you know anyone who has experience with Service Workers I could message?
matteo
July 19, 2021, 9:36pm
15
Not a clue, and most likely this isn’t the best place to find one.
1 Like
system
Closed
July 22, 2021, 9:37pm
16
This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.