I have a camera module with a WiFi chip that runs its own HTTP/websocket server. A GUI can be accessed by opening the address '192.168.1.1' in a browser (Chrome).
This GUI allows to control the camera and change some parameters from the camera module.
If I open the Network monitoring in Chrome, I can see that when the camera is activated, a stream of jpg images are received by the browser.
I would like to read this stream of data (images) using Python in order to real-time process them, for example with openCV. To do so, I was using the websocket package, but I receive the Following Error:
[Errno 111] Connection refused - goodbye
[Errno 111] Connection refused
### closed ###
My current python code is:
import websocket
import _thread
import time
import rel
def on_message(ws, message):
print(message)
def on_error(ws, error):
print(error)
def on_close(ws, close_status_code, close_msg):
print("### closed ###")
def on_open(ws):
print("Opened connection")
websocket.enableTrace(True)
ws = websocket.WebSocketApp("wss://192.168.1.1",
on_open=on_open,
on_message=on_message,
on_error=on_error,
on_close=on_close)
ws.run_forever(dispatcher=rel)
rel.signal(2, rel.abort)
rel.dispatch()
Can someone please tell me what is wrong and how should I proceed?
Related
My websocket client is trying to talk to a remote wss server, and is failing with this output:
[my-user#my-server]$ python my_websocket_client.py
ws-client connecting...
[Errno 111] Connection refused
conn closed
exception in main: 'NoneType' object has no attribute 'status'
ws-client connect status is not ok.
trying to reconnect
ws-client connecting...
[Errno 111] Connection refused
conn closed
exception in main 'NoneType' object has no attribute 'status'
...and it just repeats that over and over.
Here's the relevant code (client side):
def on_error(ws, error):
logger.error("on error is: %s" % error)
def reconnect():
global reconnect_count
logger.warning("ws-client connect status is not ok.\ntrying to reconnect for the %d time" % reconnect_count)
reconnect_count += 1
if reconnect_count < RECONNECT_MAX_TIMES:
thread.start_new_thread(connect, ())
def on_message(ws, message):
message_json = json.loads(message)
payload = base64_decode_as_string(message_json["payload"])
# handler payload
try:
message_handler(payload)
except Exception as e:
logger.error("handler message, a business exception has occurred,e:%s" % e)
send_ack(message_json["messageId"])
def on_close(obj):
logging.critical("Connection closed!")
obj.close()
global connect_status
connect_status = 0
def connect():
logger.info("ws-client connecting...")
ws.run_forever(sslopt=SSL_OPT, ping_interval=PING_INTERVAL_SECONDS, ping_timeout=PING_TIMEOUT_SECONDS)
def send_ack(message_id):
json_str = json.dumps({"messageId": message_id})
ws.send(json_str)
def main():
header = {"Connection": "Upgrade",
"username": ACCESS_ID,
"password": gen_pwd()}
websocket.setdefaulttimeout(CONNECT_TIMEOUT_SECONDS)
global ws
ws = websocket.WebSocketApp(get_topic_url(),
header=header,
on_message=on_message,
on_error=on_error,
on_close=on_close)
thread.start_new_thread(connect, ())
while True:
time.sleep(CHECK_INTERVAL_SECONDS)
global reconnect_count
global connect_status
try:
if ws.sock.status == 101:
# annoying
# print("ws-client connect status is ok.")
reconnect_count = 1
connect_status = 1
except Exception:
connect_status = 0
reconnect()
if __name__ == '__main__':
main()
Also, ws.sock is None.
The reason, I think, is because the server is trying to make a connection back to the client to a high port number; however, only a few ports like 80, 443 are available to reach back to the client.
I see in my code it uses run_forever. The documentation says this function has arguments for proxies, but the documentation doesn't give an overview of that process, isn't clear how to make that happen, and doesn't show what that looks like conceptually.
How can I make the server send messages to a proxy on port 443, which in turn talks to my websocket client, to help it overcome the unavailability of other port numbers?
Or, even better, how can I make the client tell the server to connect back to it only on port 443?
Note: I'm asking the question because there are conceptual things I don't understand and aren't clear in any of the available documentation. If it was, I wouldn't be asking.
The server administrator had to open up the port.
He opened up the port the client was connecting to, say 1234. This was surprising because I thought the WS server connected back to the client on a random high port. Either he opened up an outgoing port or WS has the server try the same port number. I don't know, but that's what fixed it.
I'm using Python to connect to a websocket that generates real-time market data. In order to obtain my data I need to follow these 3 steps:
1 - Estabilish a connection with the websocket
2 - Insert the token using the message: {"action":"initialData", "token": "MY_TOKEN"}
3 - Execute the desired request which in my case is: {"action": "startStreamQuote","symbols":["PETR4"]}
This is what I've writen so far:
url = "wss://svc.aebroadcast.com.br/stock/ws"
ws = create_connection(url)
ws.recv()
ws.send(json.dumps({"action":"initialData", "token": "eY6Hw9olpa93......"}))
ws.recv()
ws.send(json.dumps({"action": "startStreamQuote","symbols":["PETR4"]}))
ws.recv()
print("Received" + ws.recv())
The following code creates the connection and pulls the information but then stops so I need to keep executing it if I wanna see more info, but if I execute 2 times and there's no new info, it gets duplicated. Anyway...
I was reading the websocket documentation and found this example for long-lived connections:
import websocket
import _thread
import time
import rel
def on_message(ws, message):
print(message)
def on_error(ws, error):
print(error)
def on_close(ws, close_status_code, close_msg):
print("### closed ###")
def on_open(ws):
print("Opened connection")
if __name__ == "__main__":
websocket.enableTrace(True)
ws = websocket.WebSocketApp("wss://api.gemini.com/v1/marketdata/BTCUSD",
on_open=on_open,
on_message=on_message,
on_error=on_error,
on_close=on_close)
ws.run_forever(dispatcher=rel) # Set dispatcher to automatic reconnection
rel.signal(2, rel.abort) # Keyboard Interrupt
rel.dispatch()
Although this example fits very well and succeeds in mainting an open connection running, I don't know where I should insert my two requests (2 and 3 of the list above) 'initialData' and 'startStreamQuote' into this structure. I've tried using ws.send(json.dumps('.....generical request.....')) and depending on the position inside the code it returns a connection closed error or simply doesn't return anything about the request.
Can someone help me with that?
I am using the Python websocket-client library to create a long running websocket connection: https://pypi.org/project/websocket-client
When using a short connection with the websocket.WebSocket class I could add the max_queue and max_size parameters to the connect() method, however I have a long running connection.
How could I change the max_queue and max_size settings using the websocket.WebsocketApp class?
import websocket
import _thread
import time
import rel
def on_message(ws, message):
print(message)
def on_error(ws, error):
print(error)
def on_close(ws, close_status_code, close_msg):
print("### closed ###")
def on_open(ws):
print("Opened connection")
if __name__ == "__main__":
websocket.enableTrace(True)
ws = websocket.WebSocketApp("wss://api.gemini.com/v1/marketdata/BTCUSD",
on_open=on_open,
on_message=on_message,
on_error=on_error,
on_close=on_close)
ws.run_forever(dispatcher=rel) # Set dispatcher to automatic reconnection
rel.signal(2, rel.abort) # Keyboard Interrupt
rel.dispatch()
I hope somebody can help me out.
good morning.
I'm trying to make an API for Quotex.com brokerage where your communication is done via websocket --> wss://ws.qxbroker.com/socket.io/?EIO=3&transport=websocket
To connect to the broker I'm using Selenium. I can recover the session, but the difficulty is to send this data back to the websocket.
My code is this, where I try to connect and then send an order to broker.
Could someone help me please.
order = '42["orders/open",{"asset":"AUDCAD_otc","amount":6,"time":1637893200,"action":"put","isDemo":1,"requestId":1637892541,"optionType":1}]'
order2 = json.dumps(order)
try:
import thread
except ImportError:
import _thread as thread
import time
def on_message(ws, message):
print(message)
def on_error(ws, error):
print(error)
def on_close(ws):
print("### closed ###")
def on_open(ws):
def run(*args):
for i in range(3):
time.sleep(1)
ws.send("""42["authorization",{"session":""" + session + ""","isDemo":1}]""")
time.sleep(1)
ws.send(order)
ws.send(order2)
ws.close()
print("thread terminating...")
thread.start_new_thread(run, ())
urlsocket = "wss://ws.qxbroker.com/socket.io/?EIO=3&transport=websocket"
ws = websocket.WebSocketApp(
urlsocket, on_message=on_message,
on_open=on_open)
ws.run_forever()
Example of analysis via google chrome devtools
Exemple Send Order for Broker
I am trying to set up a websocket on python (3.9.0) with visual studio code on MacOS X (11.2.3).
Regrettably I don't get the connection running. I immediately receive a "closed connection" output.
I already have tried to run the code on PyCharm... same result. I have already googled, but no offered solution was helpful for me.
Here is my code, it is absolutely basic:
import websocket
SOCKET = "wss://echo.websocket.org"
def on_open(ws):
print('opened connection')
ws.send("hi")
def on_close(ws):
print('closed connection')
def on_message(ws, message):
print(message.upper())
ws.close()
ws = websocket.WebSocketApp(SOCKET, on_open=on_open,
on_close=on_close, on_message=on_message)
ws.run_forever()
Thank you very much for your help.
Best wishes.