12
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

岩手県立大学Advent Calendar 2017

Day 8

Node.jsでElixir/PhoenixのChannelに接続する

Last updated at Posted at 2017-12-07

Phoenix ChannelにNode.jsからアクセスしてみます。

岩手県立大学アドベントカレンダーに差し込みました

画面左がPhoenix Channelで作っているチャット、右側のターミナルがNode.jsのプロセスです。

Phoenix ChannelのNode.js Client

phoenix-channelsを使いました。

npm i --save phoenix-channels
app.js
'use strict';

const { Socket } = require('phoenix-channels')
const socket = new Socket("ws://localhost:4000/socket");
socket.connect();
const channel = socket.channel("chat:lobby", {});

channel.join()
    .receive('ok', resp => console.log(`> joining channel  ${channel.topic}`))
    .receive("error", reason => console.log(`Error joining channel:`, reason));

channel.on("new_msg", msg => console.log(msg));

channel.onError(e => console.log("something went wrong", e))

これだけで接続できます。
簡単。

ハマってたところ

ここまでいくのに割とハマったのが

const socket = new Socket("ws://localhost:4000/socket");

とするところを

const socket = new Socket("ws://localhost:4000");

と指定していたのが問題でした。

[debug] ** (Phoenix.Router.NoRouteError) no route found for GET /websocket (DemoWeb.Router)

などのログがでてるけどさっぱりでした汗

この辺を見るとendpoint.ex

socket "/socket", MyAppWeb.UserSocket

の記述がWebSocketのパスを指定してる箇所だとわかります。

12
2
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
12
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?