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
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}`);
});
Create Angular App:
Create an Angular app using the Angular CLI:
ng new angular-socketio-app
cd angular-socketio-app
Integrate Socket.IO Client in Angular:
Install the socket.io-client library:
npm install socket.io-client
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');
});
}
}
Run the Applications:
Start the Node.js server:
node index.js
In a separate terminal, start the Angular app:
ng serve
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:
Top comments (0)