2

我开始学习 Erlang,希望为实时多人游戏创建游戏服务器。目前,我正在尝试估计 Erlang 与 Scala 相比会造成的工作量和头痛。所以,首先,我正在创建一个简单的 Erlang 服务器进程。我找到了Jesse Farmer的一个很好的教程,我已经对其进行了修改以了解更多信息。我修改后的代码类似于他的回显服务器,除了它接受英文单词并简单地返回 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

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

4

1 回答 1

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,
于 2012-08-26T19:48:12.550 回答