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

Yaws 2.0.6参照《Building Web Applications with Erlang》样例实现WebSocket连接故障求助

排查建议

  • 首先修正服务端路由逻辑错误:你当前嵌入式代码里的out函数判断逻辑完全颠倒,Upgrade请求头存在才是合法的WebSocket握手请求,你现在的代码是检测到Upgrade头就拒绝请求,反过来了,改成如下逻辑:
out(Arg) ->
   case get_upgrade_header(Arg#arg.headers) of
   true ->
       error_logger:info_msg("Starting web socket~n"),
       {websocket, sole_callback, []};
   false ->
       error_logger:warning_msg("Not a web socket client~n"),
       {content, "text/plain", "You're not a web sockets client! Go away!"}
   end.
  • 适配Yaws 2.0.6的WebSocket回调接口:你所用的教材对应Yaws版本较老,2.0+版本的WebSocket回调模块要求必须实现以下标准回调函数,仅handle_message/1已经不符合接口要求,补充缺失的回调:
-module(sole_callback).
-export([handle_open/1, handle_message/2, handle_close/2, handle_info/2, say_hi/1]).

handle_open(State) ->
    {ok, State}.

handle_message({text, Message}, State) ->
    io:format("Got text message: ~p~n", [Message]),
    {reply, {text, Message}, State};
handle_message({binary, Message}, State) ->
    io:format("~p:~p basic echo handler got ~p~n", [?MODULE, ?LINE, Message]),
    {reply, {binary, Message}, State}.

handle_close(_Reason, _State) ->
    ok.

handle_info(_Info, State) ->
    {ok, State}.

say_hi(Pid) ->
    io:format("asynchronous greetings~n", []),
    yaws_api:websocket_send(Pid, {text, <<"hi there!">>}).
  • 修正客户端JS错误:
    1. 删除代码末尾多余的Upgrade: WebSocket无效行
    2. 修正DOM ID拼写错误,$('div#message')改为$('div#messages'),避免消息无法渲染
    3. 删除img标签里的onclick=socket.onopen()逻辑,WebSocket的onopen是连接建立后自动触发的事件回调,手动调用无意义还会引发异常
  • 验证Yaws配置:确认yaws.conf中对应监听端口的server块没有禁用WebSocket,可添加配置websocket_timeout = 30000避免连接刚建立就被超时断开
  • 抓包验证握手流程:打开浏览器开发者工具的「网络」标签,筛选「WS」请求,查看WebSocket握手请求的响应状态码是否为101 Switching Protocols,如果不是,根据响应状态码排查对应问题:404说明路径配置错误,400说明握手参数不匹配,500说明服务端代码执行报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 08:54:09