服务端
from geventwebsocket import WebSocketApplication
from flask_sockets import Sockets
from flask import Flask, Blueprint
sockets = Sockets(app)
ws = Blueprint(r'ws', __name__)
sockets.register_blueprint(ws, url_prefix=r'/')
app = Flask(__name__)
class EchoApplication(WebSocketApplication):
def on_open(self):
LOGGER.info(u'有人连接啦')
self.ws.send(u'connection success')
def on_message(self, message):
try:
if isinstance(message, dict):
message = json.dumps(message)
LOGGER.info(u'接收数据:%s' % (message))
message = json.loads(message)
msg_type = message["type"]
except:
self.send_error('unknow message!')
return
# sid = request.sid
# return
if msg_type == 'heart_msg':
self.handle_online_device(message)
return
if msg_type == 'authentication':
self.ws.send(json.dumps({}))
else:
self.send_error(u'身份认证失败', operation=u'authentication')
self.ws.close()
return
def on_close(self, reason):
print(u'有人断开了,hhhhhhh')
if __name__ == "__main__":
from werkzeug.debug import DebuggedApplication
from app.websocket.websocket import EchoApplication
from geventwebsocket import Resource, WebSocketServer
WebSocketServer(('0.0.0.0', 8084),
Resource([('/', EchoApplication), ('^/.*', DebuggedApplication(app))]), debug=False).serve_forever()
客户端
from websocket import create_connection
ws = create_connection("ws://localhost:5000/echo")
ws.send("Hello, linyk3")
result = ws.recv()
print(result)
ws.close()