重新加载后重复通道连接

时间:2016-11-02 22:25:34

标签: elixir phoenix-framework phoenix-channels

我已经使用Phoenix Channels在我的项目中分配颜色,并且我一直收到这样的错误:

[debug] Duplicate channel join for topic "colors:*" in EveryColor.ColorSocket. Closing existing channel for new join

如何复制:

  1. make install&& make build
  2. mix phoenix.server
  3. 加载网页一次,一切正常
  4. 重新加载并且新颜色按钮停止工作,上面的消息显示在控制台中..
  5. 代码:

    后端

    defmodule EveryColor.DistributionChannel do
      use Phoenix.Channel
    
      alias EveryColor.Distributor
    
      def join("colors:"<>_ , _message, socket) do
        #send(self, :after_join)
        {:ok, %{color: Distributor.random_color, counter: Distributor.get_counter+1} ,socket}
      end
    
      def handle_info(:after_join, socket) do
        broadcast_counter socket
        push socket, "color_generated", %{color: Distributor.random_color}
        {:noreply, socket}
      end
    
      def handle_in("get", _payload, socket) do
        broadcast_counter socket
        {:reply, {:ok, %{color: Distributor.random_color}}, socket}
      end
    
      def broadcast_counter(socket) do
        broadcast socket, "counter_bump", %{counter: Distributor.get_counter+1}
      end
    
    end
    

    前:

    import { Socket } from 'phoenix-socket';
    import { store } from './App.jsx';
    
    let channel;
    
    export default function connectToSocket(channelName) {
    
      const logs = process.env.NODE_ENV === 'development'
            ? { logger: ((kind, msg, data) => { console.log(`kind: ${kind}: msg: ${msg}`, data); })}
            : { };
    
      const socket = new Socket(`ws:localhost:4000/socket`, logs);
    
      socket.connect();
    
      socket.onOpen( e => console.log('Socket onOpen: ', e));
      socket.onError( e => console.log('Socket onError: ', e));
      socket.onClose( e => console.log('Socket onClose: ', e));
    
      channel = socket.channel(channelName);
      channel.join(5000)
        .receive('ok', data => {
          store.dispatch({type: 'NEXT_COLOR', color: data.color });
          store.dispatch({type: 'UPDATE_COUNTER', counter: data.counter });
        })
        .receive('error', err => {
          console.log(err);
        });
    
      channel.on('color_generated', payload => {
        console.log(payload.color);
        store.dispatch({type: 'NEXT_COLOR', color: payload.color });
      });
    
      channel.on('counter_bump', payload => {
        store.dispatch({type: 'UPDATE_COUNTER', counter: payload.counter });
      });
    
    }
    
    export function dispatchSocketMessage(message) {
      return new Promise((resolve, reject) => {
        channel.push(message)
          .receive('ok', resolve)
          .receive('err', reject);
      });
    }
    

    回购:

    1. Front
    2. Backend

0 个答案:

没有答案