Last active
August 21, 2019 21:24
-
-
Save gilons/a6a453d5ab7b70e4c2fae4c77b9af7a3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module(socket). | |
-export([start/0, start_socket/1]). | |
start() -> spawn_link(?MODULE, start_socket, [self()]). | |
start_socket(Pid) -> | |
{ok, ListenSocket} = gen_tcp:listen(3555, | |
[{active, true}, {reuseaddr, true}]), | |
connection(ListenSocket, Pid). | |
loop(Socket, Pid, Datar) -> | |
case gen_tcp:recv(Socket, 0, 5000) of | |
{ok, Data} when Data =/= <<4>> -> | |
case string:find(Data, "_start_") of | |
nomatch -> | |
case string:find(Data, "_end_") of | |
nomatch -> loop(Socket, Pid, [Datar, Data]); | |
_ -> | |
Final = [Datar, string:replace(Data, "_end_", "")], | |
io:format("~w ~n", | |
[jsx:decode(erlang:list_to_binary(Final), | |
[return_maps])]), | |
loop(Socket, Pid, <<"">>) | |
end; | |
_ -> | |
NewData = string:replace(Data, "_start_", ""), | |
case string:find(Data, "_end_") of | |
nomatch -> loop(Socket, Pid, [Datar, NewData]); | |
_ -> | |
Final = string:replace(NewData,"_end_",""), | |
jsx:decode(Final), | |
io:format("~s ~n", [jsx:decode(Final, [return_maps])]), | |
loop(Socket, Pid, <<"">>) | |
end | |
end; | |
_ -> ok = Pid:close(Socket) | |
end. | |
connection(ListenSocket, Pid) -> | |
inet:setopts(ListenSocket, [{active, false}]), | |
{ok, Socket} = gen_tcp:accept(ListenSocket), | |
loop(Socket, Pid, <<"">>). | |
%% it should be noted that, for my case, the client have the "_start_" string at the beginning and the string "_end_" at the end of the sent data. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment