Websocket Worker Relay

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,
				},
			})
		}), )
});

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.

That solved nothing… It’s only three backticks before and after.

1 Like

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,
				},
			})
		}), )
}); 

Magically, it worked.

1 Like

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

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

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

As I am not paid, nor employed by Cloudflare that isn’t really convincing me… :slight_smile:

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

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?

It doesn’t require CF skills, it’s simply a matter of a good web developer that has experience with Service Workers.

Do you know anyone who has experience with Service Workers I could message?

Not a clue, and most likely this isn’t the best place to find one.

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.