user2484294
user2484294

Reputation: 107

Kicking clients from server (Erlang)

I'm new to Erlang and I am writing a basic server. 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.

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.

Upvotes: 1

Views: 108

Answers (2)

0xAX
0xAX

Reputation: 21817

Use when you need close a TCP socket and kill process:

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

Upvotes: 1

拿小xi的铅笔
拿小xi的铅笔

Reputation: 74

You can close a socket by killing the pid, like this:

erlang:exit(Pid, kill)

Upvotes: 1

Related Questions