Erlang TCP服务器处理

时间:2012-08-26 18:52:00

标签: tcp erlang

我开始学习Erlang,希望为实时多人游戏创建游戏服务器。目前,我正在尝试估计Erlang对Scala造成的工作和头痛。所以,首先,我正在创建一个简单的Erlang服务器进程。我找到了Jesse Farmer的一个很好的教程,我已经修改了它以了解更多信息。我的修改后的代码与他的echo服务器类似,只是它接受英文单词并简单地返回Lojban等价物。但是,只选择了通配符。这是代码:

-module(translate).
-export([listen/1]).
-import(string).

-define(TCP_OPTIONS, [binary, {packet, 0}, {active, false}, {reuseaddr, true}]).

% Call echo:listen(Port) to start the service.
listen(Port) ->
    {ok, LSocket} = gen_tcp:listen(Port, ?TCP_OPTIONS),
    accept(LSocket).

% Wait for incoming connections and spawn the echo loop when we get one.
accept(LSocket) ->
    {ok, Socket} = gen_tcp:accept(LSocket),
    spawn(fun() -> loop(Socket) end),
    accept(LSocket).

% Echo back whatever data we receive on Socket.
loop(Socket) ->
    case gen_tcp:recv(Socket, 0) of
        {ok, Data} ->
            case Data of
                "Hello" -> gen_tcp:send(Socket, "coi\n");
                "Hello\n" -> gen_tcp:send(Socket, "coi\n");
                'Hello' -> gen_tcp:send(Socket, "coi\n");
                <<"Hello">> -> gen_tcp:send(Socket, "coi\n");
                <<"Hello\n">> -> gen_tcp:send(Socket, "coi\n");
                _ -> gen_tcp:send(Socket, "I don't understand")
            end,
            loop(Socket);
        {error, closed} ->
            ok
    end.

我目前的测试是打开两个终端窗口并执行

[CONSOLE 1]
erl
c(translate).
translate:listen(8888).

[CONSOLE 2]
telnet localhost 8888
whatever
Hello

输出变为:

I don't understand
I don't understand

如何解析传入的数据?这种模式匹配似乎完全失败了。谢谢!

1 个答案:

答案 0 :(得分:2)

试试这个:

case binary_to_list(Data) of
    "Hello\r\n" -> gen_tcp:send(Socket, "this will be good variant\n");
    _ -> gen_tcp:send(Socket, "I don't understand")
end,

或者没有明确的转换:

case Data of
    <<"Hello\r\n">> -> gen_tcp:send(Socket, "this will be good variant\n");
    _ -> gen_tcp:send(Socket, "I don't understand")
end,

从评论中更新

要处理更复杂的匹配,请先删除"\r\n"后缀:

Content = list_to_binary(lists:subtract(binary_to_list(Data), "\r\n")),
case Content of
    <<"Hello">> -> gen_tcp:send(Socket, <<"Good day!\n">>);
    <<"My name is, ", Name/binary>> -> gen_tcp:send(Socket, <<"Hello ", Name/binary, "!\n">>);
    _ -> gen_tcp:send(Socket, "I don't understand")
end,
相关问题