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}.