Reputation: 4676
I am using the elixir-socket library. I would like to be able to connect to a test server running within the same erlang/elixir enviroment so I can test the messages sent. when I try to use the elixir socket to connect to localhost I get a non-existing domain error.
As an example I have a test that just prints messages a webserver receives to illustrate the point.
defmodule MyTest do
use ExUnit.Case
test "socket" do
port = 9999
SingleServer.start_link(port)
:timer.sleep(2_000)
socket = Socket.Web.connect! "0.0.0.0:#{port}"
socket |> Socket.Web.send! { :text, "test" }
:timer.sleep(2_000)
end
end
defmodule SingleServer do
def start_link(port) do
spawn_link __MODULE__, :init, [port]
end
def init(port) do
server = Socket.Web.listen! port
client = server |> Socket.Web.accept!
client = server |> Socket.Web.accept!
client |> Socket.Web.recv! |> IO.inspect
end
end
Upvotes: 3
Views: 1225
Reputation: 23164
On the client side to connect to a host/port use either the two-argument connect!
or connect!
passing in a pair:
Socket.Web.connect!("localhost", port)
|> Socket.Web.send!({ :text, "test" })
On the server side somewhat counterintuitively accept!
seems to be doing something different depending on if you pass it a server or a client socket. If you pass a server it waits for a client to connect and returns the client socket. If you pass the client socket it "accepts" the connection (as opposed to close!
ing it), so the server side code should be something like:
server = Socket.Web.listen!(port)
client = Socket.Web.accept!(server)
Socket.Web.accept!(client)
client |> Socket.Web.recv! |> IO.inspect
Upvotes: 2