无法获得PubNub React Chat教程

时间:2017-02-08 23:17:30

标签: reactjs webrtc pubnub

我正在尝试运行PubNub React Realtime Chat应用程序的生产版本 (https://www.pubnub.com/blog/2016-06-14-getting-started-with-pubnub-and-react/)我希望其他用户通过IP地址访问此应用程序。但是,当我运行生产版本时。似乎PubNub后端服务根本不起作用。我无法从PubNub订阅中收到任何消息。无法检查哪些用户在线。所以,我试图在我的数字海洋服务器上运行开发版本。同样的事情发生了。没有来自PubNub服务器的响应。你能帮我解决这个问题吗?

以下是我的node-server config

const express = require('express');
const winston = require('winston');
const helmet = require('helmet');
const nodeProxy = require('./node-proxy');
const nodeAppServer = require('./node-app-server');
const Yelp = require("yelp");
// const http = require('http');

/**
 * Heroku-friendly production http server.
 *
 * Serves your app and allows you to proxy APIs if needed.
 */

const app = express();
// const server = http.createServer(app);

const PORT = process.env.PORT || 8080;

// Enable various security helpers.
app.use(helmet());


// API proxy logic: if you need to talk to a remote server from your client-side
// app you can proxy it though here by editing ./proxy-config.js
nodeProxy(app);

// Serve the distributed assets and allow HTML5 mode routing. NB: must be last.
nodeAppServer(app);

// Start up the server.
app.listen(PORT, '10.18.217.126', (err) => {
  if (err) {
    winston.error(err);
    return;
  }

  winston.info(`Listening on port ${PORT}`);
});

这是PubNub订阅:

import React from 'react';
import {connect} from 'react-redux';
import {setCurrentUserID, addMessage, addUser, removeUser, addMarker} from '../action';
import ChatInput from '../components/ChatInput';
import ChatHistory from '../components/ChatHistory';
import ChatUsers from '../components/ChatUsers';

const ID = Math.round(Math.random() * 1000000);
const pubnub = PUBNUB.init({
  publish_key: ‘my key',
  subscribe_key: ‘my key',
  uuid: ID,
  ssl: (location.protocol.toLowerCase() === 'https:'), // encrypt the channel
});

function mapStateToProps(state) {
  console.log(state.app.get('markers').toJS());
  return {
    history: state.app.get('messages').toJS(),
    userID: state.app.get('userID'),
    users: state.app.get('users').toJS(),
    markers: state.app.get('markers').toJS(),
    send_marker: state.app.get('send_marker'),
    // usersLocation: state.app.get('usersLocation').toJS(),
  };
}

function mapDispatchToProps(dispatch) {
  return {
    addMessage: (message) => dispatch(addMessage(message)),
    setUserID: (userID) => dispatch(setCurrentUserID(userID)),
    addUser: (userID) => dispatch(addUser(userID)),
    removeUser: (userID) => dispatch(removeUser(userID)),
    addMarker: (userData) => dispatch(addMarker(userData)),
    // sendMarker: (marker) => dispatch(sendMarker(marker)),
  };
}

class App extends React.Component {

  static propTypes = {
    markers: React.PropTypes.array,
    history: React.PropTypes.array,
    userID: React.PropTypes.number,
    addMessage: React.PropTypes.func,
    setUserID: React.PropTypes.func,
    users: React.PropTypes.array,
    addUser: React.PropTypes.func,
    removeUser: React.PropTypes.func,
    addMarker: React.PropTypes.func,
    sendMarker: React.PropTypes.func,
  };

  constructor(props) {
    super(props);
    this.state = {
      active: 'FIRST',
      searchBar: '',
      searchedPOI: '',
      mainNav: 'ORIGIN',
      currentLoc: '',
      goToMarker: '',
      fromWhereToMap: '',
    };
  }

  componentWillMount() {
    this.fetchData();
    navigator.geolocation.getCurrentPosition((position) => {
      this.setState({
        currentLoc: [position.coords.latitude, position.coords.longitude]
      });
    });
  }

  componentDidMount() {
    console.log(this.state.searchedPOI);
    // No geo location here you said?
    this.props.setUserID(ID);
    navigator.geolocation.getCurrentPosition((position) => {
      pubnub.subscribe({
        channel: 'ReactChat',
        message: this.props.addMessage,
        presence: this.onPresenceChange,
        state: {
          id: ID,
          lat: position.coords.latitude,
          lng: position.coords.longitude,
        },
      });
    });
    const self = this;
    pubnub.here_now({
      channel: 'ReactChat',
      state: true,
      uuids: true,
      callback: function(response) {
        console.log(response);
        response.uuids.map((uuid) => {
          self.props.addMarker(uuid.state);
        });
      },
    });
    window.addEventListener('beforeunload', this.leaveChat);
  }

  componentWillUnmount() {
    this.leaveChat();
  }

  onPresenceChange = (presenceData) => {
    switch (presenceData.action) {
      case 'join':
        // this.props.addUser([presenceData.uuid, presenceData.data.lat, presenceData.data.lng]);
        if (presenceData.data) {
          this.props.addMarker(presenceData.data);
        }
        this.props.addUser(presenceData.uuid);
        break;
      case 'leave':
        this.props.removeUser(presenceData.uuid);
        break;
      case 'timeout':
        this.props.removeUser(presenceData.uuid);
        break;
      default:
        console.error('unknown action: ' + presenceData.action);
    }
  }


  render() {
    const {props, sendMessage, state} = this;
    const active = state.active;
    const mainNav = state.mainNav;
    const searchPOI = state.searchBar;
    return (
      <div>
              <ChatUsers users={ props.users }
                     focusModal={this.onToggleNav.bind(this)}
                     currentPage={active}
                     toggleFunction={this.handleClick.bind(this)}
          />

<ChatHistory
              history={ props.history }
              getMarker={this.getMarker.bind(this)}
              me={ props.userID }
            />
<ChatInput userID={ props.userID } sendMessage={ sendMessage }/>
          </div>
)

  sendMarker(marker) {
    console.log(marker);
  }


  leaveChat = () => {
    pubnub.unsubscribe({channel: 'ReactChat'});
  };

  sendMessage = (message) => {
    pubnub.publish({
      channel: 'ReactChat',
      message: message,
    });
  };

}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(App);

0 个答案:

没有答案