【问题标题】:What is the easiest way to communicate between Javascript web script to an Erlang server在 Javascript Web 脚本与 Erlang 服务器之间进行通信的最简单方法是什么
【发布时间】: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}.

【问题讨论】:

标签: javascript json websocket erlang cowboy


【解决方案1】:

我找到了这个例子

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));

【讨论】:

    猜你喜欢
    • 2015-07-13
    • 2019-04-20
    • 2018-05-31
    • 2015-01-10
    • 2010-10-06
    • 2011-03-19
    • 1970-01-01
    • 2010-12-20
    • 2011-09-17
    相关资源
    最近更新 更多