FastAPI: WebSocket connection close after ~40s - websocket

I try to ping/pong json packages between a FastAPI websocket endpoint and a client using the websocket library from Zephyr RTOS. Unfortunately the connection is closed by the FastAPI server after ~40 seconds. This time seems to be constant. My guess is, that there must occur a timeout event due to a missing/wrong condition.
This post seems to address my issue. Unfortunately my code is not running with a newer uvicorn version which would support --ws-ping-interval or --ws-ping-timeout.
For a simple test I did the following:
Server side:
#app.websocket("/ws/update_status")
async def websocket_endpoint(websocket: WebSocket, db: Session = Depends(get_db)):
await websocket.accept()
while True:
data = await websocket.receive_json()
await websocket.send_json('{"status":"ok"}')
Client side (C code running on Zephyr-RTOS):
// some code to define JSON package
while(1)
{
websocket_send_msg(sock, send_buffer, json_length, WEBSOCKET_OPCODE_DATA_TEXT, true, true, SYS_FOREVER_MS);
websocket_recv_msg(sock, receive_buffer, sizeof(receive_buffer), &message_type, 0, SYS_FOREVER_MS);
}
I use the following package versions:
uvicorn=='0.13.4'
fastapi=='0.68.2'
Does anyone know why the connection aborts after 40 seconds and how it can be avoided?

Related

How to deploy and interact with a rust websocket?

I'm a beginner in Rust and WebSockets and I'm trying to deploy on Heroku a little chat backend I wrote (everything works on localhost). The build went well and I can see the app is running, and I'm now trying to connect to the WebSocket from a local HTML/Javascript frontend, but it is not working.
Here is my code creating the WebSocket on my rust server on Heroku (using the tungstenite WebSocket crate):
async fn main() -> Result<(), IoError> {
let port = env::var("PORT").unwrap_or_else(|_| "8080".to_string());
let addr = format!("0.0.0.0:{}", port);
// Create the event loop and TCP listener we'll accept connections on.
let try_socket = TcpListener::bind(&addr).await;
let listener = try_socket.expect("Failed to bind");
println!("Listening on: {}", addr);
and here is the code in my Javascript file that tries to connect to that WebSocket:
var ws = new WebSocket("wss://https://myappname.herokuapp.com/");
My web client gets the following error in the console:
WebSocket connection to 'wss://https//rocky-wave-51234.herokuapp.com/' failed
I searched to find the answer to my issue but unfortunately didn't find a fix so far. I've found hints that I might have to create an HTTP server first in my backend and then upgrade it to a WebSocket, but I can't find a resource on how to do that and don't even know if this is in fact the answer to my problem. Help would be greatly appreciated, thanks!
I think your mistake is the URL you use:
"wss://https://myappname.herokuapp.com/"
A URL usually starts with <protocol>://. The relevant protocols here are:
http - unencrypted hypertext
https - encrypted hypertext
ws - unencrypted websocket
wss - encrypted websocket
So if your URL is an encrypted websocket, it should start only with wss://, a connection cannot have multiple protocols at once:
"wss://myappname.herokuapp.com/"

Elixir erlang :ftp.send got stuck

I use Erlang ftp lib in my elixir project to send file to ftp server.
I call send function :ftp.send(pid, '#{local_path}', '#{remote_path}') to upload file to ftp server.
Most of the time it uploads files successfully, but it sometimes stuck here, not moving to the next line.
According to the docs it should return :ok or {:error, reason}, but simply stuck at :ftp.send.
Can anyone give me suggestion? I am not familiar with Erlang.
Version: Elixir 1.7.3 (compiled with Erlang/OTP 21)
ftp module has two types of timeout, both set during the initialization of ftp service.
Here is an excerpt from the documentation:
{timeout, Timeout}
Connection time-out. Default is 60000 (milliseconds).
{dtimeout, DTimeout}
Data connect time-out. The time the client waits for the server to connect to the data socket. Default is infinity.
Data connect time-out has a default value of infinity, meaning it’d be hang up if there are some network issues. To overcome the problem, I’d suggest you set this value to somewhat meaningful and handle timeouts in your application appropriately.
{:ok, pid} = :ftp.start_service(
host: '...', timeout: 30_000, dtimeout: 10_000
)
:ftp.send(pid, '#{local_path}', '#{remote_path}')

connecting autobahn websocket server to crossbar.io router

I have an application that connects to a web page that sends and receives text strings over a websocket on port 1234. I do not have access to the front end code, so I cannot change the HTML front end code.
I created an autobahn server with a class derived from WebSocketServer protocol that communicates with the web page over port 1234. This works and I am able to send and receive text to the front end.
However, I need to process incoming data and would like to publish the received data to a crossbar.io container through the router on port 8080 (or any other port). The port to the web browser is fixed at 1234.
It there a way for me to "plug in " the autobahn websocket server into the crossbar router or is there an alternative way to create a websocket server that will allow me to to send and receive the text on port 1234 and at the same time participate in pub/sub and RPC with the crossbar router?
I am assuming you are using Python. If you are not, the answer should still be the same, but depending on the language/library and its implementation the answer can change.
From what you are saying, it does not sound like you really need a "plug in". Crossbar does have these under the description of router components. But unless you really need to attach a Python instance directly to the router either for performance or otherwise, I would recommend keeping your application off the router. It would work perfectly fine as a stand alone instance especially if it is on the same machine where the WAMP router is located where the packets would only require to communicate over loopback (which is VERY fast).
Given that you are using Python:
You can use your WebSocketServer and a WampApplicationServer together. The little hiccup you might run into is starting them up properly. In either scenario Python2.x with twisted or Python3.4 with Asyncio you can only start the reactor/event loop once or an error will ensue. (Both Twisted and Asyncio have the same basic concept) In Asyncio you will get RuntimeError: Event loop is running. if you attempt to start the event loop twice. Twisted has a similar error. Using the ApplicationRunner in twisted, there is an option (second argument in run) not to start up the reactor which you can use after the reactor is already running. In Asyncio, there is no such option, the only way I found out how to do it is to inherit the Application runner and overwrite the run method to start the session to be started as a task. Also, be warned that threads do not cooperate with either event loop unless properly wrapped.
Once you have the two connections set up in one instance you can do whatever you want with the data.
Thanks for the idea, and the problems you mention are exactly what I encountered. I did find a solution however, and thanks to the flexibility of crossbar, created a JavaScript guest that allows me to do exactly what I need. Here is the code:
// crossbar setup
var autobahn = require('autobahn');
var connection = new autobahn.Connection({
url: 'ws://127.0.0.1:8080/ws',
realm: 'realm1'
}
);
// Websocket to Scratch setup
// pull in the required node packages and assign variables for the entities
var WebSocketServer = require('websocket').server;
var http = require('http');
var ipPort = 1234; // ip port number for Scratch to use
// this connection is a crossbar connection
connection.onopen = function (session) {
// create an http server that will be used to contain a WebSocket server
var server = http.createServer(function (request, response) {
// We are not processing any HTTP, so this is an empty function. 'server' is a wrapper for the
// WebSocketServer we are going to create below.
});
// Create an IP listener using the http server
server.listen(ipPort, function () {
console.log('Webserver created and listening on port ' + ipPort);
});
// create the WebSocket Server and associate it with the httpServer
var wsServer = new WebSocketServer({
httpServer: server
});
// WebSocket server has been activated and a 'request' message has been received from client websocket
wsServer.on('request', function (request) {
// accept a connection request from Xi4S
//myconnection is the WS connection to Scratch
myconnection = request.accept(null, request.origin); // The server is now 'online'
// Process Xi4S messages
myconnection.on('message', function (message) {
console.log('message received: ' + message.utf8Data);
session.publish('com.serial.data', [message.utf8Data]);
// Process each message type received
myconnection.on('close', function (myconnection) {
console.log('Client closed connection');
boardReset();
});
});
});
};
connection.open();

Unable to reconnect SignalR JS client after recycle of application pool

When i recycle my Application Pool for the site where the SignalR hub is running, the javascript clients is unable to reconnect. But everything is OK if the client do a refresh on his browser.
In the clients console log, these lines repeat multiple times every second after a reset of the app pool: ( i have replaced the connection token with abcd )
LOGG: [15:51:19 UTC+0200] SignalR: Raising the reconnect event
LOGG: [15:51:19 UTC+0200] SignalR: An error occurred using longPolling. Status = parsererror. undefined
LOGG: [15:51:19 UTC+0200] SignalR: SignalR: Initializing long polling connection with server.
LOGG: [15:51:19 UTC+0200] SignalR: Attempting to connect to 'http://lab/signalr/reconnect?transport=longPolling&connectionToken=abcd' using longPolling.
LOGG: [15:51:19 UTC+0200] SignalR: Raising the reconnect event
I have tried disabling all authentication on the hub, but still the same result.
Both the server and client is running on SignalR v1.0.1
The hubconnection on the client is set up like this:
var connection = $.hubConnection('http://lab:8097', { logging: true });
var proxy = connection.createHubProxy('task');
connection.start({ jsonp: true }).done(function () {
proxy.invoke('OpenTask', id);
});
Im also using crossdomain on the server side hub registration:
RouteTable.Routes.MapHubs(new HubConfiguration { EnableCrossDomain = true });
The server is running on IIS 7.5, and the client is IE9.
Anyone have an idea what's wrong?
This issue will be resolved in 1.1 RTW (not released yet, currently only the beta is out).
For your reference here's the fix: https://github.com/SignalR/SignalR/issues/1809. If you'd like to have the fix earlier you can implement the changes noted in the issue.
Lastly, if you do choose to implement the fix you will need to handle the .disconnected event on the connection and restart the connection entirely.

force client disconnect from server with socket.io and nodejs

Is there any way to disconnect a client with SocketIO, and literally close the connection? So if someone is connected to my server, and I want to close the connection between them and my server, how would I go about doing that?
Edit: This is now possible
You can now simply call socket.disconnect() on the server side.
My original answer:
This is not possible yet.
If you need it as well, vote/comment on this issue.
socket.disconnect() can be used only on the client side, not on the server side.
Client.emit('disconnect') triggers the disconnection event on the server, but does not effectively disconnect the client. The client is not aware of the disconnection.
So the question remain : how to force a client to disconnect from server side ?
Any reason why you can't have the server emit a message to the client that makes it call the disconnect function?
On client:
socket.emit('forceDisconnect');
On Server:
socket.on('forceDisconnect', function(){
socket.disconnect();
});
Checking this morning it appears it is now:
socket.close()
https://socket.io/docs/client-api/#socket-close
For those who found this on google - there is a solution for this right now:
Socket.disconnect() kicks the client (server-side). No chance for the client to stay connected :)
Assuming your socket's named socket, use:
socket.disconnect()
This didn't work for me:
`socket.disconnect()`
This did work for me:
socket.disconnect(true)
Handing over true will close the underlaying connection to the client and not just the namespace the client is connected to Socket IO Documentation.
An example use case: Client did connect to web socket server with invalid access token (access token handed over to web socket server with connection params). Web socket server notifies the client that it is going to close the connection, because of his invalid access token:
// (1) the server code emits
socket.emit('invalidAccessToken', function(data) {
console.log(data); // (4) server receives 'invalidAccessTokenEmitReceived' from client
socket.disconnect(true); // (5) force disconnect client
});
// (2) the client code listens to event
// client.on('invalidAccessToken', (name, fn) => {
// // (3) the client ack emits to server
// fn('invalidAccessTokenEmitReceived');
// });
In my case I wanted to tear down the underlying connection in which case I had to call socket.disconnect(true) as you can see is needed from the source here
client._onDisconnect() should work
I'm using client.emit('disconnect') + client.removeAllListeners() for connected client for ignore all events after disconnect
Socket.io uses the EventEmitter pattern to disconnect/connect/check heartbeats so you could do. Client.emit('disconnect');
I am using on the client side socket.disconnect();
client.emit('disconnect') didnt work for me
You can do socket = undefined in erase which socket you have connected. So when want to connected do socket(url)
So it will look like this
const socketClient = require('socket.io-client');
let socket;
// Connect to server
socket = socketClient(url)
// When want to disconnect
socket = undefined;
I have using the socket client on React Native app, when I called socketIOClient.disconnect() this disconnects from the server but when I connect to the socket again the previous events were connected again, and the below code works for me by removing all existing events and disconnecting socket conneciton.
socketIOClient.removeAllListeners();
socketIOClient.disconnect(true);
To disconnect socket forcefully from server side
socket.disconnect(true)
OR
To disconnect socket by client side event
On client:
socket.emit('forceDisconnect');
On Server:
socket.on('forceDisconnect', function(){
socket.disconnect(true);
});
You can call socket.disconnect() on both the client and server.
Add new socket connections to an array and then when you want to close all - loop through them and disconnect. (server side)
var socketlist = [];
io.sockets.on('connection', function (socket) {
socketlist.push(socket);
//...other code for connection here..
});
//close remote sockets
socketlist.forEach(function(socket) {
socket.disconnect();
});
use :
socket.Disconnect() //ok
do not use :
socket.disconnect()

Resources