code

code

Why does the program exit when I try to take input?

def handle_client(client) do
        msg = IO.gets("> ") |> String.trim
        :gen_tcp.send(client, buffering(msg))
        :gen_tcp.send(client, msg)
end

When I replace the function that takes input(I tried IO.gets/1 and IO.read/2) with a normal string, the message is sent normally.

Here is the function that listens and accepts connections(irrelevant, I think ?)

def listen_and_accept(ip_addr) do
        case :gen_tcp.listen(8000, [:binary, active: false, reuseaddr: true, ip: ip_addr]) do
            {:ok, server} ->
                IO.puts "Listening..."
                case :gen_tcp.accept(server) do
                    {:ok, client} ->
                        IO.puts "Client accepted"
                        spawn fn -> handle_client(client) end
                    {:error, reason} ->
                        IO.puts "Error in :gen_server.accept: #{reason}"
                end
            {:error, reason} -> IO.puts "Error in :gen_tcp.listen: #{reason}"
        end
end

Thanks in advance guys.

Marked As Solved

aseigo

aseigo

IO.gets/2 takes a device and a prompt, default to stdio, which is a shortcut to Process.group_leader/0 according to the docs … the spawn changes the process group leader and so it probably just sits there forever waiting for I/O from a process that never comes.

If you wish to send user input from the console to the connection, you’re going to probably want to send msgs to the connection handlers from a process accepting input from a console.

Also Liked

aseigo

aseigo

That’s about right, yes. You’ll want to take input from console, and then use message passing to get it into your client handler process.

However, that is a bit of an odd pattern in your code. Essentially, what it is doing is waiting for a client connection, then spawning an asynchronous process to handle that connection while the next connections may come in. So you can easily have N of these handlers running concurrently. Which one gets which user input?

If you really want to handle one connection at a time with user interaction, then don’t spawn the client connection handler (avoiding creating a separate process) and just handle it as you have now all in the main process (which presumably you are running from the REPL?).

But yes, that’s why what you have isn’t working as you expected, though the solution may involve changing how your program works a bit to actually fit your goals :slight_smile:

Welcome to Elixir, btw… it’s certain to be a fun journey!

Where Next?

Popular in Questions Top

itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
Fl4m3Ph03n1x
Background Let’s assume I have a typical GenServer that receives messages as requests, does some operation in a DB and returns responses....
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
chewm
Hi guys, nice to meet you to the whole forum, I’m new here, I’m trying to configure visual studio code for elixir, right now the intellis...
New

Other popular topics Top

dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
sergio
I couldn’t find any guides that worked well with Phoenix 1.6.0 and esbuild. I hope this helps people test the waters and eases you into t...
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New

We're in Beta

About us Mission Statement