1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
| import select import socket import threading
from flask import Flask from flask_sockets import Sockets from gevent import pywsgi from geventwebsocket.handler import WebSocketHandler
app = Flask(__name__) sockets = Sockets(app)
class Config(object): SOCKET_HOST = '127.0.0.1' SOCKET_PORT = 2020
def read_thread_method(sock,socket_lock,ws): while True: if not sock: break rs, _, _ = select.select([sock], [], [], 10) for r in rs: socket_lock.acquire()
if not sock: socket_lock.release() break try: data = r.recv(1024) except Exception as e: data = None
socket_lock.release()
if not data: print('server close') else: print(data) ws.send(data.decode())
def start_client(ws):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((Config.SOCKET_HOST, Config.SOCKET_PORT)) socket_lock = threading.Lock()
read_thread = threading.Thread(target=read_thread_method, args=(sock,socket_lock,ws)) read_thread.setDaemon(True) read_thread.start()
return sock,socket_lock,read_thread
@sockets.route('/') def echo_socket(ws):
print('当前/:', ws) sock,socket_lock,read_thread = start_client(ws) print("连接了poll") while not ws.closed:
message = ws.receive() print("\n message:",message,type(message)) print("ws.closed:", ws.closed) if message: ws.send("callback") sock.send(message.encode()) if ws.closed: print("关闭了 sock " socket_lock.acquire() sock.close() socket_lock.release()
if __name__ == "__main__":
try: server = pywsgi.WSGIServer(('0.0.0.0', 2021), application=app, handler_class=WebSocketHandler) print("websocket server start ... ") server.serve_forever() except Exception as e: print('error:',e)
|