【发布时间】:2019-01-08 18:01:42
【问题描述】:
您好,我正在学习 Erlang 的课程,并且在期末项目中我决定制作网页游戏。 我在用 Erlang 编写的服务器使用牛仔,我卡在客户端和服务器之间传输数据的过程中。 我能够成功建立websocket连接,但是我发现传输json数据很困难。
如何获取客户端发给服务器端的信息?
客户端websocket连接是这样建立的:
socket = new WebSocket("ws://" + window.location.host + "/websocket");
socket.onopen = function(evt) { onOpen(evt) };
而客户端发送json:
var data = {x_val: x,y_val: y};
socket.send(data);
带有 websocket 处理程序的牛仔服务器代码
-module(ws_handler).
-export([init/2]).
-export([websocket_init/1]).
-export([websocket_handle/2]).
-export([websocket_info/2]).
init(Req, Opts) ->
{cowboy_websocket, Req, Opts}.
websocket_init(State) ->
io:fwrite("connection establish !~n", []),
erlang:start_timer(1000, self(), <<"Hello!">>),
{ok, State}.
websocket_handle({text, Msg}, State) ->
{reply, {text, << "That's what she said! ", Msg/binary >>}, State};
websocket_handle(_Data, State) ->
io:format("_Data -> Erlang\n~p\n",[_Data]),
{ok, State}.
websocket_info({timeout, _Ref, Msg}, State) ->
erlang:start_timer(1000, self(), <<"How' you doin'?">>),
{reply, {text, Msg}, State};
websocket_info(_Info, State) ->
{ok, State}.
【问题讨论】:
-
您的代码似乎直接来自 Cowboy 的示例:github.com/ninenines/cowboy/tree/master/examples/websocket 您是否设法在没有修改的情况下运行上述示例?
标签: javascript json websocket erlang cowboy