[英]communicate between python script on server side and javascript in the web-browser
[英]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.