-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlcsynctest
More file actions
executable file
·117 lines (98 loc) · 2.16 KB
/
lcsynctest
File metadata and controls
executable file
·117 lines (98 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#!/usr/bin/env escript
-import(lists,[map/2,flatten/1,sublist/3,sublist/2,split/2,nthtail/2]).
main(Args)->
set_defaults(),
ok=parse_args(Args),
ok=connect(),
try
keyboard()
after
disconnect()
end.
set_defaults()->
put(port,1024),
put(host,"localhost").
parse_args([])->ok;
parse_args(["--port",P|T])->
put(port,list_to_integer(P)),
parse_args(T);
parse_args(["--host",H|T])->
put(host,H),
parse_args(T);
parse_args(Args)->
io:format("Wrong args: ~p~n",[Args]),
{wrong_args,Args}.
connect()->
{ok,S}=gen_tcp:connect(get(host),get(port),
[list,{active,false},{packet,4}]),
put(socket,S),
ok.
disconnect()->
gen_tcp:close(get(socket)).
keyboard()->
case read_message() of
[] -> done;
M ->
ok=send_message(M),
net()
end.
net()->
case recv_message() of
[] -> done;
M ->
write_message(M),
keyboard()
end.
read_message()->
case io:get_line("") of
"\n" -> [];
Str when is_list(Str) andalso length(Str)>1 ->
Str2=lists:sublist(Str,length(Str)-1),
[process_string(Str2) | read_message()];
_ -> []
end.
process_string([])->[];
process_string([$\\])->[$\\];
process_string([$\\,$x,Dh,Dl|T]) ->
case erlang:list_to_integer([Dh,Dl],16) of
D when is_integer(D) ->
[D];
_ -> [$\\,$x,Dh,Dl]
end ++ process_string(T);
process_string([$\\,C|T])->
case [C] of
"n" -> "\n";
"t" -> "\t";
"0" -> [0];
_ -> [$\\,C]
end ++ process_string(T);
process_string([H|T])->
[H|process_string(T)].
write_message(M)->
io:format("~p~n",[M]).
recv_message()->
{ok,P}=gen_tcp:recv(get(socket),0),
unmarshal(P).
send_message(M)->
ok=gen_tcp:send(get(socket),marshal(M)).
% from util.erl
marshal(List) ->
L = int2list(length(List)),
LS = map(fun (X)->int2list(length(X)) end,List),
L ++ flatten(LS) ++ flatten(List).
unmarshal(List)->
L = list2int(sublist(List,1,4)),
LS = lengths(sublist(List,1+4,4*L)),
extractLists(LS,nthtail(4*(L+1),List)).
extractLists([],[])->[];
extractLists([L|LS],XS)->
{X,Rest}=split(L,XS),
[X|extractLists(LS,Rest)].
lengths([])->[];
lengths(XS)->
{V,Rest}=split(4,XS),
[list2int(V)|lengths(Rest)].
list2int(L)->
<<I:32/integer>> =list_to_binary(L), I.
int2list(I)->
binary_to_list(<<I:32/integer>>).