Hello All. I am looking at using Elixir to build a game server for a side project.
The plan is to use Websockets for the greatest mix of compatibility and security.
So found a simple hello world test and put it into vscode (running on Mac).
When I tried to launch it from the command line VS Code had already launched the webserver automatically.
Can someone explain to me what is happening? Not sure if it is a misconfiguration of mix or something else.
Code bellow. Thanks All!
# mix.exs
defmodule PlugServerProto.MixProject do
use Mix.Project
def project do
[
app: :plug_server_proto,
version: "0.1.0",
elixir: "~> 1.17",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger]
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
{:bandit, "~> 1.0"}
# {:dep_from_hexpm, "~> 0.3.0"},
# {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}
]
end
end
# plug_server_proto.ex
defmodule PlugServerProto do
require Logger
require Router
webserver = {Bandit, plug: Router, scheme: :http, port: 4000}
{:ok, _} = Supervisor.start_link([webserver], strategy: :one_for_one)
Logger.info("Plug now running on localhost:4000")
Process.sleep(:infinity)
end
# echo_server.ex
defmodule EchoServer do
def init(options) do
{:ok, options}
end
def handle_in({"ping", [opcode: :text]}, state) do
{:reply, :ok, {:text, "pong"}, state}
end
def terminate(:timeout, state) do
{:ok, state}
end
end
# router.ex
defmodule Router do
use Plug.Router
plug Plug.Logger
plug :match
plug :dispatch
get "/" do
send_resp(conn, 200, """
Use the JavaScript console to interact using websockets
sock = new WebSocket("ws://localhost:4000/websocket")
sock.addEventListener("message", console.log)
sock.addEventListener("open", () => sock.send("ping"))
""")
end
get "/websocket" do
conn
|> WebSockAdapter.upgrade(EchoServer, [], timeout: 60_000)
|> halt()
end
match _ do
send_resp(conn, 404, "not found")
end
end