You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala是否支持非流式WebSocket?目前似乎无法实现

在JavaScript和Python中快速搭建WebSocket服务

在日常开发中,我发现用JavaScript(Node.js)和Python来构建WebSocket服务器或客户端是相当便捷的,几行核心代码就能实现基础的消息收发功能。

JavaScript(Node.js)示例

用Node.js搭建WebSocket服务器的话,借助ws库可以快速实现,下面是一段极简的示例代码:

const WebSocket = require('ws');
// 创建WebSocket服务器,监听8080端口
const wss = new WebSocket.Server({ port: 8080 });

// 监听客户端连接事件
wss.on('connection', function connection(ws) {
  // 监听客户端发来的消息
  ws.on('message', function incoming(message) {
    console.log('received: %s', message);
  });

  // 主动给客户端发送欢迎消息
  ws.send('已成功连接到WebSocket服务器!');
});

你只需要先通过npm install ws安装依赖,运行这段代码就能启动一个基础的WebSocket服务器,客户端连接后就能双向收发消息了。

Python示例

Python这边,websockets库是个不错的选择,同样用几行代码就能搞定:

import asyncio
import websockets

# 处理客户端连接的异步函数
async def handle_client(websocket):
    # 接收客户端消息
    received_msg = await websocket.recv()
    print(f'received: {received_msg}')
    # 回复客户端
    await websocket.send('已成功连接到Python WebSocket服务器!')

# 启动服务器
async def start_server():
    async with websockets.serve(handle_client, 'localhost', 8765):
        await asyncio.Future()  # 让服务器持续运行

asyncio.run(start_server())

安装依赖用pip install websockets,运行后就能在本地8765端口启动WebSocket服务啦。

内容的提问来源于stack exchange,提问作者CubemonkeyNYC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:13:35