概要
paiza.ioでelixirやってみた。
tcpでserver,clientやってみた。
サンプルコード
defmodule Server do
require Logger
use GenServer
@port 8000
def start do
GenServer.start(__MODULE__, %{socket: nil})
end
def init(state) do
{:ok, socket} = :gen_tcp.listen(@port, [:binary, active: true])
send(self(), :accept)
Logger.info "Accepting connection on port #{@port}..."
{:ok, %{state | socket: socket}}
end
def handle_info(:accept, %{socket: socket} = state) do
{:ok, _} = :gen_tcp.accept(socket)
Logger.info "Client connected"
{:noreply, state}
end
def handle_info({:tcp, socket, data}, state) do
Logger.info "Received #{data}"
Logger.info "Sending it back"
:ok = :gen_tcp.send(socket, data)
{:noreply, state}
end
def handle_info({:tcp_closed, _}, state), do: {:stop, :normal, state}
def handle_info({:tcp_error, _}, state), do: {:stop, :normal, state}
end
Server.start
IO.puts "ok0"
{:ok, socket} = :gen_tcp.connect('localhost', 8000, [:binary, active: false])
IO.puts "ok1"
:ok = :gen_tcp.send(socket, "msg")
IO.puts "ok2"
{:ok, data} = :gen_tcp.recv(socket, 0)
data
|> IO.puts
実行結果
05:56:00.149 [info] Accepting connection on port 8000...
ok0
ok1
05:56:00.153 [info] Client connected
ok2
msg
05:56:00.153 [info] Received msg
05:56:00.153 [info] Sending it back
成果物
以上。