Esente
Esente
Explore posts from servers
CDCloudflare Developers
Created by Esente on 4/16/2024 in #workers-help
TCP Socket does not seem to work on Worker
I have created a new worker using the example on https://developers.cloudflare.com/workers/runtime-apis/tcp-sockets/#connect (also below), under https://connect.fifo.workers.dev When trying to access https://connect.fifo.workers.dev/gopher/wbgopher, it takes a long time and just returns a blank page. It seems to stuck at responding with the ReadableStream from socket. Code from the example:
import { connect } from 'cloudflare:sockets';

export default {
async fetch(req: Request) {
const gopherAddr = { hostname: "gopher.floodgap.com", port: 70 };
const url = new URL(req.url);

try {
const socket = connect(gopherAddr);

const writer = socket.writable.getWriter()
const encoder = new TextEncoder();
const encoded = encoder.encode(url.pathname + "\r\n");
await writer.write(encoded);

return new Response(socket.readable, { headers: { "Content-Type": "text/plain" } });
} catch (error) {
return new Response("Socket connection failed: " + error, { status: 500 });
}
}
};
import { connect } from 'cloudflare:sockets';

export default {
async fetch(req: Request) {
const gopherAddr = { hostname: "gopher.floodgap.com", port: 70 };
const url = new URL(req.url);

try {
const socket = connect(gopherAddr);

const writer = socket.writable.getWriter()
const encoder = new TextEncoder();
const encoded = encoder.encode(url.pathname + "\r\n");
await writer.write(encoded);

return new Response(socket.readable, { headers: { "Content-Type": "text/plain" } });
} catch (error) {
return new Response("Socket connection failed: " + error, { status: 500 });
}
}
};
5 replies