提问人:Extra Acc 提问时间:11/13/2023 最后编辑:Extra Acc 更新时间:11/13/2023 访问量:24
未收到 Websocket 到客户端的消息 - Cloudflare
Websocket to client message not received - Cloudflare
问:
您好,我是 cloudflare websockts 的新手。我有下面的 cloudflare worker 代码和 js 代码。当有效负载内容“完成”发送给工作线程时,它应该返回“服务器收到”完成“消息。但我什么也没收到。我正在使用 Chrome 的开发者控制台来执行 JS 代码。
Cf 工人代码 :
addEventListener('fetch', (event) => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
const upgradeHeader = request.headers.get('Upgrade');
if (!upgradeHeader || upgradeHeader !== 'websocket') {
return new Response('Expected Upgrade: websocket', { status: 426 });
}
const webSocketPair = new WebSocketPair();
const [client, server] = Object.values(webSocketPair);
server.accept();
// Event listener for the 'message' event on the server WebSocket
server.addEventListener('message', (event) => {
console.log('Received message from client:', event.data);
// Check if the received message is 'done'
if (event.data === 'done') {
// Send a response back to the client
client.send('Server received "done" message.');
}
});
// Return the server WebSocket without closing it
return new Response(null, {
status: 101,
webSocket: server,
});
}
Js 客户端代码:
const wsUrl = 'wss://worker.subdomain.workers.dev';
const socket = new WebSocket(wsUrl);
socket.addEventListener('open', (event) => {
console.log('WebSocket connection opened:', event);
// Send a plain text message
const plainTextMessage = 'done'; //here is the payload
socket.send(plainTextMessage);
});
socket.addEventListener('message', (event) => {
console.log('Received message:', event.data);
// You can handle the received message here
// If the received message is a JSON string, you can parse it back to an object
try {
const receivedJson = JSON.parse(event.data);
console.log('Parsed JSON:', receivedJson);
} catch (error) {
console.log('Received plain text message:', event.data);
}
});
socket.addEventListener('error', (event) => {
console.error('WebSocket error:', event);
});
socket.addEventListener('close', (event) => {
console.log('WebSocket connection closed:', event);
});
在这里,我要求向客户发送消息。client.send('Server received "done" message.');
当客户端发送“完成”时,cloudflare worker 的预期响应是:“服务器收到”完成“消息。
简而言之,服务器应发送“服务器收到”完成“消息。TO CLIEN,当客户端发送到服务器时完成。
答: 暂无答案
评论