cj1128

cj1128

I implemented a simple echo server in Elixir, repo is here GitHub - cj1128/echo_server · GitHub.

When I test it using echo hello | nc localhost 4100, everything is fine.

But when I use a custom client which concurrently starts 10 connections, I got below error, so confused.

13:25:12.299 [error] Task #PID<0.108.0> started from #PID<0.95.0> terminating
** (MatchError) no match of right hand side value: {:error, :closed}
    lib/client.exs:14: Client.run/0
    (elixir 1.14.3) lib/task/supervised.ex:89: Task.Supervised.invoke_mfa/2
    (elixir 1.14.3) lib/task/supervised.ex:34: Task.Supervised.reply/4
    (stdlib 4.2) proc_lib.erl:240: :proc_lib.init_p_do_apply/3
Function: #Function<1.124100197/0 in Client.run>
    Args: []

13:25:12.299 [error] Task #PID<0.107.0> started from #PID<0.95.0> terminating
** (MatchError) no match of right hand side value: {:error, :closed}
    lib/client.exs:14: Client.run/0
    (elixir 1.14.3) lib/task/supervised.ex:89: Task.Supervised.invoke_mfa/2
    (elixir 1.14.3) lib/task/supervised.ex:34: Task.Supervised.reply/4
    (stdlib 4.2) proc_lib.erl:240: :proc_lib.init_p_do_apply/3
Function: #Function<1.124100197/0 in Client.run>
    Args: []

I tried

  • sysctl kern.ipc.somaxconn=1000 increase TCP queue size
  • Add an accept pool, so multiple processes are accepting connections

none of them worked, still got those errors.

Env

OS: ARM64 and X64 MacOS 12.3

$ elixir --version
Erlang/OTP 25 [erts-13.1.3] [source] [64-bit] [smp:10:10] [ds:10:10:10] [async-threads:1] [jit] [dtrace]

Elixir 1.14.3 (compiled with Erlang/OTP 25)

How to run

$ mix run --no-halt
# in another shell
$ elixir lib/client.exs
Summary

This text will be hidden

Showing Posts 1 to 9

al2o3cr

al2o3cr

EchoServer calls accept in one process, then recv in a different, newly-spawned one.

The process that calls accept “owns” the connection (see also recent discussion here).

cj1128

cj1128 OP

Hi, thanks for you reply.

My code is not the same as the linked one, the main process which owns the connection is always alive, so it should not cause the socket to be closed.

I modified the code to use :gen_tcp.controlling_process and I still got the error.

defmodule EchoServer do
  require Logger

  def start do
    {:ok, socket} = :gen_tcp.listen(4100, [:binary, active: false, packet: :line])
    Logger.info("Starting echo server")
    accept(socket)
  end

  defp accept(socket) do
    {:ok, conn} = :gen_tcp.accept(socket)
    pid = spawn(fn -> recv(conn) end)
    :ok = :gen_tcp.controlling_process(conn, pid)
    send(pid, :start)
    accept(socket)
  end

  defp recv(conn) do
    receive do
      :start ->
        echo(conn)
    end
  end

  defp echo(conn) do
    case :gen_tcp.recv(conn, 0) do
      {:ok, data} ->
        :gen_tcp.send(conn, data)
        echo(conn)

      {:error, :closed} ->
        :ok
    end
  end
end

When I ran the client, sometimes it’s all fine, sometimes I got {:error, :closed}, and sometimes I got {:error, :econnreset}.

cj1128

cj1128 OP

I wrote a simple echo server in JS and I tested it using the same client elixir lib/client.exs and I found that no error showed, so I am sure that something is wrong with my server code, but I am really confused what is going wrong.

const net = require("net")

const server = net.createServer((socket) => {
  console.log("Client connected")

  socket.on("data", (data) => {
    console.log(`Received data: ${data}`)
    socket.write(data)
  })
})

server.listen(4100, () => {
  console.log("Server listening on port 4100")
})
jnnks

jnnks

This snippet works for me using telnet.
Could you reduce your code a bit more?

cj1128

cj1128 OP

Hi, telnet is fine, but the server returned error when it was concurrently requested.

This is the reduced code.

defmodule EchoServer do
  require Logger

  def start do
    {:ok, socket} = :gen_tcp.listen(4100, [:binary, active: false, packet: :line])
    Logger.info("Starting echo server")
    accept(socket)
  end

  defp accept(socket) do
    {:ok, conn} = :gen_tcp.accept(socket)
    pid = spawn(fn -> recv(conn) end)
    :ok = :gen_tcp.controlling_process(conn, pid)
    send(pid, :start)
    accept(socket)
  end

  defp recv(conn) do
    receive do
      :start ->
        echo(conn)
    end
  end

  defp echo(conn) do
    case :gen_tcp.recv(conn, 0) do
      {:ok, data} ->
        :gen_tcp.send(conn, data)
        echo(conn)

      {:error, :closed} ->
        :ok
    end
  end
end

EchoServer.start()
defmodule Client do
  require Logger

  def start() do
    for _ <- 1..10 do
      Task.async(&run/0)
    end
    |> Task.await_many()
  end

  def run() do
    {:ok, socket} = :gen_tcp.connect(~c"localhost", 4100, [:binary, packet: :line, active: false])
    :ok = :gen_tcp.send(socket, "hello\n")

    case :gen_tcp.recv(socket, 0) do
      {:ok, "hello\n"} ->
        Logger.info("ok")

      other ->
        Logger.error("error: #{inspect(other)}")
    end
  end
end

Client.start()
jnnks

jnnks

This example also works fine for me :smiley:
I ran it in two separate iex sessions.

cj1128

cj1128 OP

This is very weird, can you try to run the client multiple times? it’s not always erroring out.

If I ran the client against the node version server, then i will always succeed.

jnnks

jnnks

Running multiple clients also works for me.
Maybe you can try to isolate your error even further. No Logger, no modules, etc.
As long as the behavior is inconsistent I don’t think we can help you that well.

cj1128

cj1128 OP

Finally found the reason.

The default backlog param of :gen_tcp is 5 and this is too small. When the TCP accept queue is full, we will get error like “error: closed”

— All posts loaded —

Where Next? Top

Trending in Questions Top

katta
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
achenet
Hello, I’m trying to build a basic Phoenix web-app, and I’d like to use Tailwind. However, when I launch mix phx.server, I get an error...
New
bradley
I really like the adapter patterns that ecto, nebulex, waffle, etc. use and would love find something similar for a key management servic...
New
unaware8150
Hello folks! So at work, we are seeing some situations where we have to define some “fixed” strings that are used across the codebase in...
New
Cxx-mlr
I’m working on a small exercise involving update_in/3, and I came up with this solution: data = %{ name: "Periodic Table", category:...
New
ChrisAmelia
I’ve got trouble wrapping my head around the order in which functions are called in this snippet (from Phoenix’s authentication): toke...
New
dillonoconnor
Is there any way to avoid the Hologram compiler running when using iex? It seems like the front-end code could potentially be disregarded...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
New
KristerV
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
mudasobwa
I fully migrated to my own harness from Anthropic/Gemini and I think it’s time to share it. Welcome DSH, the DeepSeek Harness, fully writ...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews