Reputation: 23
I am new to web socket, i'm implementing web socket server using flask-socketio, and angular-socketio as client,
i use this code in flask
application.py
@socketio.on('connect', namespace='/test')
def test_connect():
print('Client connected')
and i use this code in angular service to connect to flask server
socket.service.ts
import { Injectable } from "@angular/core";
import * as io from "socket.io-client";
import { Observable } from "rxjs";
@Injectable({
providedIn: "root"
})
export class SocketService {
private socket;
constructor() {
this.socket = io("/test"); // i get example by connect using flask namespace
this.socket = io("localhost:5000"); // i tried this
this.socket = io(`/api`); // i also tried this
}
public sendMessage(message) {
this.socket.emit("new-message", message);
}
public getMessages = () => {
return Observable.create(observer => {
this.socket.on("new-message", message => {
observer.next(message);
});
});
};
}
i also try to connect to flask server using localhost:5000 as the URL, but it leads CORS problem, and after facing that issue i also try to connect using '/api' from proxy.config.json below as the url
{
"/api": {
"target": "http://127.0.0.1:5000",
"secure": false,
"pathRewrite": {
"^/api": ""
}
}
}
this is my app.component
app.component.ts
import { Component } from "@angular/core";
import { SocketService } from "./socket.service";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
title = "angularsocketio";
constructor(private socketService: SocketService) {}
}
Upvotes: 2
Views: 4198
Reputation: 67492
The Socket.IO server needs to be configured appropriately if you need to access it from across domains. See the cors_allowed_origins
option in the documentation.
The default URL for a Socket.IO service is /socket.io
. Both the client and the server need to be told if you want to use a different URL. For the server, this is the path
option, also documented.
Upvotes: 2