Skip to content

Instantly share code, notes, and snippets.

@adamar
Created April 6, 2017 06:37
Show Gist options
  • Save adamar/a4c573c724f647d7fdcfce5a0f1638d9 to your computer and use it in GitHub Desktop.
Save adamar/a4c573c724f647d7fdcfce5a0f1638d9 to your computer and use it in GitHub Desktop.
Simple Websocket Client & Server Example (Python)
import websocket
import thread
import time
import sys
port = sys.argv[1]
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):
while True:
time.sleep(5)
ws.send("Hello")
time.sleep(1)
ws.close()
thread.start_new_thread(run, ())
if __name__ == "__main__":
websocket.enableTrace(True)
ws = websocket.WebSocketApp("ws://localhost:" + port + "/",
on_message = on_message,
on_error = on_error,
on_close = on_close)
ws.on_open = on_open
ws.run_forever()
from SimpleWebSocketServer import SimpleWebSocketServer, WebSocket
import sys
port = int(sys.argv[1])
class SimpleEcho(WebSocket):
def handleMessage(self):
# echo message back to client
self.sendMessage(self.data)
def handleConnected(self):
print(self.address, 'connected')
def handleClose(self):
print(self.address, 'closed')
server = SimpleWebSocketServer('', port, SimpleEcho)
server.serveforever()
@QGB
Copy link

QGB commented Jan 22, 2021

Why are you using SimpleWebSocketServer library ?

@QGB
Copy link

QGB commented Jan 22, 2021

and client.py is python2 code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment