I found this project: http://code.google.com/p/standalonewebsocketserver/ for a WebSocket server, but I need to implement a WebSocket client in python, more exactly I need to receive some commands from XMPP in my WebSocket server.
WebSocket Client with PythonCreate a new File “client.py” and import the packages as we did in our server code. Now let's create a Python asynchronous function (also called coroutine). async def test(): We will use the connect function from the WebSockets module to build a WebSocket client connection.
If you don't want to wait, let the Python process exit, then the OS will close the TCP connection. Parameters: code ( int ) – WebSocket close code. reason ( str ) – WebSocket close reason.
Start by creating a directory where we are going to serve the application—call it WebSocket. Inside the server.py file, add the following lines of code that implement a simple server on the / URL. reply = f"Data recieved as: {data}!"
websockets is a library for building WebSocket servers and clients in Python with a focus on correctness, simplicity, robustness, and performance. Built on top of asyncio , Python's standard asynchronous I/O framework, it provides an elegant coroutine-based API.
http://pypi.python.org/pypi/websocket-client/
Ridiculously easy to use.
sudo pip install websocket-client
Sample client code:
#!/usr/bin/python from websocket import create_connection ws = create_connection("ws://localhost:8080/websocket") print "Sending 'Hello, World'..." ws.send("Hello, World") print "Sent" print "Receiving..." result = ws.recv() print "Received '%s'" % result ws.close()
Sample server code:
#!/usr/bin/python import websocket import 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(30000): time.sleep(1) ws.send("Hello %d" % i) time.sleep(1) ws.close() print "thread terminating..." thread.start_new_thread(run, ()) if __name__ == "__main__": websocket.enableTrace(True) ws = websocket.WebSocketApp("ws://echo.websocket.org/", on_message = on_message, on_error = on_error, on_close = on_close) ws.on_open = on_open ws.run_forever()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With