Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to integrate Socket.io? #107

Open
abubakarmani1 opened this issue Sep 7, 2017 · 3 comments
Open

How to integrate Socket.io? #107

abubakarmani1 opened this issue Sep 7, 2017 · 3 comments
Labels

Comments

@abubakarmani1
Copy link

please help me integrating socket.io with this repo

@s-patompong
Copy link

Having the same issue, search many places and seem like socket.io will need a server instance to create the io object.

Ref: https://github.com/luixaviles/socket-io-typescript-chat/blob/master/server/src/server.ts

@DavideViolante DavideViolante changed the title How to integrate Socket.io ??? I am unable to achieve the results How to integrate Socket.io? Nov 4, 2017
@pedroraft
Copy link
Contributor

This seems like a very clean approach.
Plus it will create all sockets with no need to import.

import * as sio from 'socket.io';

const chatServer = sio({
  path: '/socket.io/chat'
});

chatServer.on('connection', (socket) => {
  console.log('a user connected');
  socket.on('chat message', (msg) => {
    console.log('message: ' + msg);
    chatServer.emit('chat message', msg);
  });
  socket.on('disconnect', () => {
    console.log('user disconnected');
  });
});

export default chatServer;

/// ________________________ later in main server file ____________________________________-
// socket.io
const sioModules = require('require-all')({
  dirname: __dirname + '/socket.io',
  filter: (filename: string) => {
    filename = filename.toLowerCase();
    if ((filename.endsWith('.ts') && !filename.endsWith('.spec.ts'))
      || (filename.endsWith('.js') && !filename.endsWith('.spec.js'))) {
      return filename.substr(0, filename.length - 3);
    }
  }
});
for (const name of Object.keys(sioModules)) {
  const exported = sioModules[name].default;
  if (exported && exported.constructor.name === 'Server') {
    console.log(`Add socket.io server ${name}`);
    const sioServer = exported as SocketIO.Server;
    sioServer.attach(server);
  }
}

@adwulfran
Copy link
Contributor

I could include socket.io doing this :

  • install socket.io
    > npm install --save socketio socket.io-client

  • I added few lines to app.ts , here after is the whole code :

import * as dotenv from 'dotenv';
import * as express from 'express';
import * as morgan from 'morgan';
import * as mongoose from 'mongoose';
import * as path from 'path';
import setRoutes from './routes';
import * as socketio from "socket.io";
const app = express();
let http = require('http').Server(app);
// set up socket.io and bind it to our
// http server.
let io = require('socket.io')(http);
dotenv.load({ path: '.env' });
app.set('port', (process.env.PORT || 3000));

app.use('/', express.static(path.join(__dirname, '../public')));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

// SOCKET.IO START
io.on('connection', (socket) => {
  console.log('new connection made');
  
  socket.on('event1', (data) => {
    console.log(data.msg);
  });
  
  socket.emit('event2', {
    msg: 'Server to client, do you read me? Over.'
  });
  
  socket.on('event3', (data) => {
    console.log(data.msg);
    socket.emit('event4', {
      msg: 'Loud and clear :)'
    });
  });
  }); 
// SOCKET.IO END

let mongodbURI;
if (process.env.NODE_ENV === 'test') {
  mongodbURI = process.env.MONGODB_TEST_URI;
} else {
  mongodbURI = process.env.MONGODB_URI;
  app.use(morgan('dev'));
}

mongoose.Promise = global.Promise;
mongoose.connect(mongodbURI)
  .then(db => {
    console.log('Connected to MongoDB');

    setRoutes(app);

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

    if (!module.parent) {
      http.listen(app.get('port'), () => console.log('Angular Full Stack listening on port ...'));
    }
  })
  .catch(err => console.error(err));

export { app };
  • Import socket on frontend side. For example let's take about.component.ts
import { Component } from '@angular/core';
import * as io from 'socket.io-client';

@Component({
  moduleId: module.id,
  selector: 'app-about',
  templateUrl: './about.component.html',
  styleUrls: ['./about.component.scss']
})
export class AboutComponent {
  messageText: string;
    messages: Array<any>;
    socket: SocketIOClient.Socket;
  constructor() {this.socket = io.connect() }
  ngOnInit() {
  this.messages = new Array();

          this.socket.on('message-received', (msg: any) => {
              this.messages.push(msg);
              console.log(msg);
              console.log(this.messages);
          });
        this.socket.emit('event1', {
            msg: 'Client to server, can you hear me server from about component?'
        });
      }
        sendMessage() {
          const message = {
            text: this.messageText
          };
          this.socket.emit('send-message', message);
          // console.log(message.text);
          this.messageText = '';
        }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

5 participants