DEV Community

Manthan Ankolekar
Manthan Ankolekar

Posted on

Setting Up a Simple Real-Time Application with Angular, Node.js, and Socket.IO

Install Dependencies:

Install Node.js and npm (Node Package Manager) on your machine if not already installed.

Create Node.js Server:

Set up a Node.js server using Express and Socket.IO. Install required packages:

npm init -y
npm install express socket.io cors
Enter fullscreen mode Exit fullscreen mode

Create a basic server in a file (e.g., index.js):

const express = require('express');
const http = require('http');
const socketIO = require('socket.io');
const cors = require("cors");

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

app.use(
    cors({
        origin: "*",
    })
);

const io = socketIO(server, {
    cors: {
        origin: "http://localhost:4200",
        methods: ["GET", "POST"]
    }
});

io.on('connection', (socket) => {
    console.log('A user connected');

    socket.on('disconnect', () => {
        console.log('User disconnected');
    });
});

const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode

Create Angular App:

Create an Angular app using the Angular CLI:

ng new angular-socketio-app
cd angular-socketio-app
Enter fullscreen mode Exit fullscreen mode

Integrate Socket.IO Client in Angular:

Install the socket.io-client library:

npm install socket.io-client
Enter fullscreen mode Exit fullscreen mode

In your Angular component, you can use Socket.IO to connect to the server:

import { Component, OnInit } from '@angular/core';
import * as io from 'socket.io-client';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  private socket: any;

  ngOnInit() {
    this.socket = io('http://localhost:3000');

    this.socket.on('connect', () => {
      console.log('Connected to server');
    });

    this.socket.on('disconnect', () => {
      console.log('Disconnected from server');
    });
  }
}
Enter fullscreen mode Exit fullscreen mode

Run the Applications:

Start the Node.js server:

node index.js
Enter fullscreen mode Exit fullscreen mode

In a separate terminal, start the Angular app:

ng serve
Enter fullscreen mode Exit fullscreen mode

Now, your Angular app and Node.js server should be running, and you can explore real-time communication using Socket.IO.

Remember that this is a basic example, and you can extend it to include more features based on your application requirements.

Reference

For detailed implementation, you can refer to the following GitHub repository:

Frontend Source Code
Backend Source Code

Top comments (0)