Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a WebSocket client implemented for Python? [closed]

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.

like image 630
diegueus9 Avatar asked Jun 29 '10 16:06

diegueus9


People also ask

How does Python connect to WebSocket client?

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.

How do I close a WebSocket in Python?

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.

How are WebSockets implemented in Python?

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}!"

Is Python good for WebSockets?

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.


1 Answers

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() 
like image 50
Bryan Hunt Avatar answered Oct 11 '22 07:10

Bryan Hunt