LoginSignup
3
0

More than 1 year has passed since last update.

paiza.ioでelixir その13

Last updated at Posted at 2022-10-25

概要

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

成果物

以上。

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0