简体   繁体   English

从服务器踢客户端(Erlang)

[英]Kicking clients from server (Erlang)

I'm new to Erlang and I am writing a basic server. 我是Erlang的新手,正在编写基本服务器。 I am trying to figure out how to correctly kick a client from the server using the information that I have about the client (which is Pid, Client_socket, and Client_name. 我试图弄清楚如何使用我拥有的有关客户端的信息(即Pid,Client_socket和Client_name)从服务器正确踢出客户端。

Any suggestions would be great and much appreciated. 任何建议将是巨大的,非常感谢。 Thanks for reading :) 谢谢阅读 :)

Here's my code so far: 到目前为止,这是我的代码:

-module(cell_clnt).

-export([cell_client/0]).

cell_client()->
    %%% Add any needed parameters for your cell process here
    Port = 21,
    Pending_connections = 5,
    Cell = fun()-> cell_process() end,
    spawn(fun()-> timer:sleep(10), keyboard_loop(Cell) end),
    receive
        stop->
            ok
    end.

keyboard_loop(Cell)->
    case io:get_line(">> ") of
        "quit\n"->
           io:fwrite("Exiting...~n"),
           if is_pid(Cell)-> Cell!stop; true->ok end;
        "start\n" when is_function(Cell)->
            keyboard_loop(spawn(Cell));
        Input when is_pid(Cell)->
            Cell!{input,Input},
            keyboard_loop(Cell);
        _Input->
            io:fwrite("No cell process active yet!~n"),
            keyboard_loop(Cell)
    end.


%%% Edit this to implement your cell process %%%
cell_process()->
    io:fwrite("In cell~n"), 
    {ok,Listening_socket} = gen_tcp:listen(21,
                                        [binary,
                                        {backlog,5},
                                        {active,false},
                                        {packet,line}]),
    loop(Listening_socket,[]).

loop(Listening_socket, Clients)->
    io:format("Clients: ~p", [Clients]),
    case gen_tcp:accept(Listening_socket) of
        {ok,Client_socket} ->   
        gen_tcp:send(Client_socket, "Hello, what is your name?"),
        {_,Name} = gen_tcp:recv(Client_socket,0),
        gen_tcp:send(Client_socket, "Hello, "),
        gen_tcp:send(Client_socket, Name),
        Pid = spawn(fun()-> client_loop(Client_socket) end),
            loop(Listening_socket,[{Pid,Client_socket,Name}|Clients])
        end.    

client_loop(Client_socket)->    
    case gen_tcp:recv(Client_socket,0) of
    {ok,Message}-> gen_tcp:send(Client_socket,Message),
        client_loop(Client_socket);

    {error,Why}-> io:fwrite("Error: ~s~n",[Why]),
        gen_tcp:close(Client_socket)
    end.

您可以通过杀死pid来关闭套接字,如下所示:

erlang:exit(Pid, kill)

Use when you need close a TCP socket and kill process: 在需要关闭TCP套接字并终止进程时使用:

gen_tcp:close(Socket)
exit(Pid, kill).

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM