In your angular application install a SocketIO package:
npm install socket.io
or for current user only ( or if you don't have admin rights 😅 )
npm install socket.io --user
In your python application you need to install socket-io library:
pip install flask-socketio
In your python file, you need to create a flask server and sockets for connection:
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
app = Flask(__name__)
SOCKETIO = SocketIO(app, cors_allowed_origins="*")
@app.route('/')
def index():
#### if you want it in your python app to return something if default route is called
return render_template('index.html')
@SOCKETIO.on('connect')
def message():
data = 'Hi, connection from flask-socketio'
emit('connect_ngsocket', {'data': data})
if __name__ == '__main__':
SOCKETIO.run(app,host='0.0.0.0',port=9000)
Then run your python application in terminal:
python app.py
This will run the socket and print some message like:
.. .. .. * Running on http://0.0.0.0:9000/ (Press CTRL+C to quit)
Here 0.0.0.0:9000 means the app is running on local IP and port 9000
In your angular typescript file, you need to call for connection.
Here I am creating an angular service to create a connection:
import { Injectable } from '@angular/core';
import io from 'socket.io-client';
@Injectable({
providedIn: 'root'
})
export class SocketConnectService {
socket: any;
constructor() {
this.socket = io.connect('http://<local IP>:9000/'); // Connection with Server using API, Enter Local IP carefully
this.socket.on('connect_ngsocket', function(CONN_MSG) {
console.log('HI, from Angular', CONN_MSG);
});
}
getConnection() {
return this.socket;
}
}
Now you can import "SocketConnectService" in components or other services and use the connection setup by the service by calling its getConnection()
method
import { Component, OnInit } from '@angular/core';
import { SocketConnectService } from './socket-connect.service';
@Component({
selector: 'app-sample',
})
export class SampleComponent implements OnInit {
socket: any;
constructor(private SCService: SocketConnectService) {
this.socket = this.SCService.getConnection();
}
ngOnInit() {
this.runTheMethod();
}
runTheMethod() {
// sending request to a python socket
this.socket.emit('call_from_ng', {
data: 'Any Data You Want To Send To Python App'
});
// recieving response from python socket
this.socket.on('response_from_py', function(RESPONSE) {
console.log(RESPONSE);
// and do whatever you want
});
}
}
@SOCKETIO.on('call_from_ng')
def handlingCallFromNg(data):
#### Do anything you want to do with the data
emit('response_from_py', { 'data' : 'Anything' }) #### Sending response from python to angular app
If you encounter a bug or problem with this sample code, please submit a new issue so we know about it and can fix it.
For general issues refer associated forums and documentation