接收消息并写入文件

发布于 2024-11-30 05:23:02 字数 3431 浏览 2 评论 0原文

我在这里创建了一个服务器来接收来自终端的消息。我想要做的是,当服务器从终端接收到消息时,它应该将其写入文件中。但我不知道该怎么做。我想过在接收函数中编写文件方法 file:openfile:write 但它没有像我想象的那样工作。

-module(tcp).

-behaviour(gen_server).

-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3, start/0, stop/0, connect/0, send/1, recv/0]).

-export([start_link/0]).

%% =============================================================================
%% EXPORTED GEN_SERVER CALLBACKS
%% =============================================================================

init([]) -> {ok, {}}.

handle_call({send, Packet}, _From, State) ->
    gen_tcp:send(State, Packet),
    io:format("Send Working\n"),
    {reply, ok, State};

handle_call(recv, _From, State) ->
     Message = gen_tcp:recv(State, 0),
    io:format("~w~n", [Message]),
    {reply, Message, State}.

handle_cast(connect, _) ->
    case gen_tcp:listen(6888, [binary]) of
    {ok, LSocket}->
        io:format("~w~n", [LSocket]),
        case gen_tcp:accept(LSocket) of 
        {ok, Socket} ->
            inet:setopts(Socket, [{active, false}]),
            io:format("accepted\n"),
            {noreply, Socket};
        Other ->
            error_logger:error_report(["An error occurred which is",Other,"in line",?LINE,"of module",?MODULE])

        end;
    {error, Reason} ->
        error_logger:error_report("An error occurred", Reason, [?LINE,?MODULE])
    end;

handle_cast(stop, State) -> {stop, normal, State}.

handle_info(_Info, State) -> {noreply, State}.

terminate(_Reason, _State) -> ok.

code_change(_OldVsn, State, _Extra) -> {ok, State}.


%% =============================================================================
%% EXPORTED CONVENIENCE FUNCTIONS TO START AND STOP THE SERVER
%% =============================================================================

start() ->
    case gen_server:start({local, ?MODULE}, ?MODULE, [], []) of
        {ok, Pid} ->
            Pid;
        Reason ->
            error_logger:error_report("An error occurred", Reason, [?LINE,?MODULE])
    end.

stop() ->
    case gen_server:cast(?MODULE, stop) of
        ok ->
            ok;
        _ ->
            {error, stop_error}
    end.


%% =============================================================================
%% PUBLIC API FUNCTIONS
%% =============================================================================

connect() -> gen_server:cast(?MODULE, connect).

send(Packet) -> gen_server:call(?MODULE, {send, Packet}).

recv() -> gen_server:call(?MODULE, recv).

write_file(Filename) ->
    {ok, IoDevice} = file:open(test.txt, [write, append]),
    ok.

start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).


%% =============================================================================
%% LOCAL FUNCTIONS
%% =============================================================================

我按照您的建议进行操作并将其实现为 handle_call 但当我运行时出现错误,

函数handle_call/3已定义错误

我完全不明白为什么会收到这个错误,因为我有3个handle_call参数并且它应该可以工作。

handle_call(write_file, Filename, S) ->
    {ok, File} = file:open(Filename, [append]),
    ok = file:write(File, S),
    ok = file:close(File).

我的API函数

write_file() -> gen_server:call(?MODULE, write_file).

I have made a server here which receives messages from the terminal. What I want to do is when the server receives the messages from the terminal it should write it into a file. But I dont know how I should do this. I thought of writing the file methods file:open, file:write in the receive functions but it didnt work out as I thought.

-module(tcp).

-behaviour(gen_server).

-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3, start/0, stop/0, connect/0, send/1, recv/0]).

-export([start_link/0]).

%% =============================================================================
%% EXPORTED GEN_SERVER CALLBACKS
%% =============================================================================

init([]) -> {ok, {}}.

handle_call({send, Packet}, _From, State) ->
    gen_tcp:send(State, Packet),
    io:format("Send Working\n"),
    {reply, ok, State};

handle_call(recv, _From, State) ->
     Message = gen_tcp:recv(State, 0),
    io:format("~w~n", [Message]),
    {reply, Message, State}.

handle_cast(connect, _) ->
    case gen_tcp:listen(6888, [binary]) of
    {ok, LSocket}->
        io:format("~w~n", [LSocket]),
        case gen_tcp:accept(LSocket) of 
        {ok, Socket} ->
            inet:setopts(Socket, [{active, false}]),
            io:format("accepted\n"),
            {noreply, Socket};
        Other ->
            error_logger:error_report(["An error occurred which is",Other,"in line",?LINE,"of module",?MODULE])

        end;
    {error, Reason} ->
        error_logger:error_report("An error occurred", Reason, [?LINE,?MODULE])
    end;

handle_cast(stop, State) -> {stop, normal, State}.

handle_info(_Info, State) -> {noreply, State}.

terminate(_Reason, _State) -> ok.

code_change(_OldVsn, State, _Extra) -> {ok, State}.


%% =============================================================================
%% EXPORTED CONVENIENCE FUNCTIONS TO START AND STOP THE SERVER
%% =============================================================================

start() ->
    case gen_server:start({local, ?MODULE}, ?MODULE, [], []) of
        {ok, Pid} ->
            Pid;
        Reason ->
            error_logger:error_report("An error occurred", Reason, [?LINE,?MODULE])
    end.

stop() ->
    case gen_server:cast(?MODULE, stop) of
        ok ->
            ok;
        _ ->
            {error, stop_error}
    end.


%% =============================================================================
%% PUBLIC API FUNCTIONS
%% =============================================================================

connect() -> gen_server:cast(?MODULE, connect).

send(Packet) -> gen_server:call(?MODULE, {send, Packet}).

recv() -> gen_server:call(?MODULE, recv).

write_file(Filename) ->
    {ok, IoDevice} = file:open(test.txt, [write, append]),
    ok.

start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).


%% =============================================================================
%% LOCAL FUNCTIONS
%% =============================================================================

I did as you suggested and implemented it as a handle_call but when i run i get an error,

function handle_call/3 already defined error

I quite dont understand why I get this error since i have 3 arguments for the handle_call and it should work.

handle_call(write_file, Filename, S) ->
    {ok, File} = file:open(Filename, [append]),
    ok = file:write(File, S),
    ok = file:close(File).

My API Function

write_file() -> gen_server:call(?MODULE, write_file).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

青春有你 2024-12-07 05:23:02

您的句柄调用不起作用,因为您有两个定义。您已经编写:

 handle_call(...) ->
   do_something.

 handle_call(M, F, S) ->
   do_some_other_thing.

您应该将它们更改为同一函数,将: 更改

   do_something.

为:

   do_something;
handle_call(M, F, S) ->
   do_some_other_thing.

Your handle call doesn't work because you have two definitions of it. You have written:

 handle_call(...) ->
   do_something.

 handle_call(M, F, S) ->
   do_some_other_thing.

You should make them into the same function, by changing:

   do_something.

into:

   do_something;
handle_call(M, F, S) ->
   do_some_other_thing.
西瓜 2024-12-07 05:23:02

write_file 应该做类似的事情:

write_file(Fname, S) ->
    ok = file:write_file(Fname, S, [append]).

或者

write_file(Fname, S) ->
    {ok, File} = file:open(Fname, [append]),
    ok = file:write(File, S),
    ok = file:close(File).

write_file should do something like:

write_file(Fname, S) ->
    ok = file:write_file(Fname, S, [append]).

or

write_file(Fname, S) ->
    {ok, File} = file:open(Fname, [append]),
    ok = file:write(File, S),
    ok = file:close(File).
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文