Overseas access: www.kdjingpai.com
Bookmark Us
Current Position:fig. beginning " AI Answers

Cloudflare Agents的WebSocket实时通信功能具体如何实现?

2025-08-30 1.2 K

实现实时通信需要前后端协同工作:

服务端配置

  1. 创建继承Agent的子类,重写连接处理方法:
    class RealtimeAgent extends Agent {
    async onConnect(ws) {
    ws.send('连接成功');
    }
    async onMessage(ws, msg) {
    ws.send(`ECHO:${msg}`);
    }
    }
  2. 部署时会自动生成wss://开头的WebSocket终结点

前端接入

  • 建立连接:const ws = new WebSocket('wss://your-agent.url')
  • 事件监听:
    ws.onopen = () => console.log('Connected');
    ws.onmessage = (e) => displayMessage(e.data);
  • 发送消息:ws.send('Hello')

Technical details:Cloudflare底层使用Durable Objects技术保证WebSocket连接的高可用性,即使代理重启也不会断开现有连接。

Recommended

Can't find AI tools? Try here!

Just type in the keyword Accessibility Bing SearchYou can quickly find all the AI tools on this site.

Top

en_USEnglish