Created
April 6, 2017 06:37
-
-
Save adamar/a4c573c724f647d7fdcfce5a0f1638d9 to your computer and use it in GitHub Desktop.
Simple Websocket Client & Server Example (Python)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why are you using SimpleWebSocketServer library ?