Friday 9 June 2017

socket.io - Not connecting to client

I have a React.js application, that uses Webpack (I'm brand new to these technologies) as its bundler. I just added socket.io to my project. socket.io requires you include a js file in the index.html, . However, when i had this in my code i kept getting io is not defined. I found a potential solution by importing socket.io.client.. While the project no runs, my server socket never picks up the connection. Anyone know what is causing this isse ?

server.js

/* eslint-disable no-console */
import express from 'express';
import webpack from 'webpack';
import path from 'path';
import config from '../webpack.config.dev';
import open from 'open';
import api from './api'; 

const port = 3000;
const app = express();
const compiler = webpack(config);
const http = require('http').Server(app);
const io = require('socket.io')(http);
// const socket = require('socket.io-client')('http://localhost');

// pass compiled webpack config file 
app.use(require('webpack-dev-middleware')(compiler, {
  noInfo: true,
  publicPath: config.output.publicPath
}));
// use hot middle ware for reloading 
app.use(require('webpack-hot-middleware')(compiler));
// api routes
app.use('/api', api);
// all request return index.html


app.get('*', function(req, res) {
  res.sendFile(path.join( __dirname, '../src/index.html'));
});
// app.use('/api', api);
// start 

//Whenever someone connects this gets executed
io.on('connection', function(socket){
  console.log('A user connected');

  //Whenever someone disconnects this piece of code executed
  socket.on('disconnect', function () {
    console.log('A user disconnected');
  });

});


app.listen(port, function(err) {
  if (err) {
    console.log(err);
  } else {
    open(`http://localhost:${port}`);
  }
});

home.component.js

import React from 'react';
import {Link} from 'react-router';
import io from 'socket.io-client';
const socket = io(`http://localhost:3000`);
class Home extends React.Component {
    render() {
        return (
            <div className="jumbotron">
            <h1>Home </h1>
        );
    }
}
export default Home;



via John

No comments:

Post a Comment