在Javascript Web脚本和Erlang服务器之间进行通信的最简单方法是什么

时间:2018-08-01 08:26:32

标签: javascript json websocket erlang cowboy

您好,我正在上Erlang课程,对于最终项目,我决定制作网络游戏。 我在使用用Erlang编写的服务器使用Cowboy,并且陷入了在客户端和服务器之间传输数据的过程。 我能够成功建立一个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}.

1 个答案:

答案 0 :(得分:2)

我找到了这个示例

https://lookonmyworks.co.uk/2014/12/21/hello-world-with-cowboy-and-websockets/

我相应地更新了ws_handler

-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, Json}, State) ->
    Map = jiffy:decode(Json, [return_maps]),
     X_val = maps:get(<<"x_val">>, Map),
     Y_val = maps:get(<<"y_val">>, Map),
     Reply = #{x_val =>X_val, y_val =>Y_val},
     {reply, {text, jiffy:encode(Reply)}, 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}.

对于我以前使用过的客户来说,

function onMessage(ev) {

 var msg = JSON.parse(ev.data);
 spaceShip.v_pos.set( msg.x, msg.y);}

和客户端传输

y = y + angle_sine*0.2*sin(angle);
x = x + angle_sine*0.2*cos(angle);

var data = {x_val: x, y_val: y };
socket.send(JSON.stringify(data));