繁体   English   中英

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

[英]What is the easiest way to communicate between Javascript web script to an Erlang server

嗨,我正在上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}.

我发现了这个例子

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM