Hi I am taking a course on Erlang, and for the final project I decided to make web game. I am using cowboy for the server written in Erlang, and I am stuck in the process of transfering data between the client and the server. I am able to successfully establish a websocket connection, but I find it hard to transfer json data.
How can I get the information sent by the client to the server side?
The client websocket connection is established like this:
socket = new WebSocket("ws://" + window.location.host + "/websocket");
socket.onopen = function(evt) { onOpen(evt) };
And the client sends json:
var data = {x_val: x,y_val: y};
socket.send(data);
The code for the cowboy server with a websocket 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, 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}.
i found this example
https://lookonmyworks.co.uk/2014/12/21/hello-world-with-cowboy-and-websockets/
i I updated accordingly the 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}.
and for the client reacive i used
function onMessage(ev) {
var msg = JSON.parse(ev.data);
spaceShip.v_pos.set( msg.x, msg.y);}
and client transmit
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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.