I am trying to develop a client to communicate with the Octoprint server. I want to receive the message from the server when I send a Gcode command by using websocket.
As shown in Octoprint server's terminal, there is a new connection from client. However, it closes immediately so that I can't send any message further.
2022-09-29 10:38:06,315 - octoprint.server.util.sockjs - INFO - New connection from client: ::1 2022-09-29 10:38:06,320 - octoprint.server.util.sockjs - INFO - Client connection closed: ::1
What did you already try to solve it?
I tried the Octoprint python client here, but it didn't work.
I guess that maybe I need to authorize it. How can I realize it by using the API key.
Have you tried running in safe mode?
Yes
Did running in safe mode solve the problem?
No
Systeminfo Bundle
You can download this in OctoPrint's System Information dialog ... no bundle, no support!)
Additional information about your setup
OctoPrint version, OctoPi version, printer, firmware, browser, operating system, ... as much data as possible
First, you have to POST /api/login, with the API key & the passive flag (exact details of this are in the API docs). Then you will receive a session key which you can send to the socket to authenticate there.
I did receive the authenticate message, like {'auth': '_api:2A97885B4F90490AA28E1C0BCD002310'}. Then I tried to send it to the socket, like ["{\"auth\": \"_api:2A97885B4F90490AA28E1C0BCD002310\"}"]
However, in the server's terminal, the connection still closed immediately.
2022-09-29 16:35:25,750 - octoprint.server.util.flask - INFO - Passively logging in user _api from ::1
2022-09-29 16:35:25,750 - octoprint.access.users - INFO - Logged in user: _api
2022-09-29 16:35:25,834 - octoprint.server.util.sockjs - INFO - New connection from client: ::1
2022-09-29 16:35:25,835 - octoprint.server.util.sockjs - INFO - User _api logged in on the socket from client ::1
2022-09-29 16:35:25,840 - octoprint.server.util.sockjs - INFO - Client connection closed: ::1`
The socket isn't a raw websocket, it speaks sockjs. So you have to encode the messages first. It's a bit messy (and due to the fact that websockets for a long time weren't as well supported as they are now, hence sockjs was chosen since it supports jsonp and other types of fallbacks), but for now it's the way things are.
Take a look at the included socket client here for how the messages need to be structured, or take a look at the sockjs docs here.
However, I got a similar error in the server's terminal.
2022-10-03 23:42:44,331 - octoprint.access.users - INFO - Logged in user: _api
2022-10-03 23:42:44,392 - octoprint.server.util.sockjs - INFO - New connection from client: 127.0.0.1
2022-10-03 23:42:45,386 - octoprint.server.util.sockjs - INFO - User _api logged in on the socket from client 127.0.0.1
2022-10-03 23:42:45,396 - octoprint.server.util.sockjs - INFO - Client connection closed: 127.0.0.1