下面是在socket.io上编写的python脚本。我有数据从服务器连续发送到Web浏览器。但是,客户端可以在其间发出'closeSSH',并且应该停止事件'nodeID'。有人可以帮我做socket.io同时听多个事件吗?
#!/usr/bin/env python
import sys
# Import 'Flask' libraries for web socket programming with the client/web-browser
from flask import Flask, render_template, request
from flask.ext.socketio import SocketIO, emit
import flask
import pxssh
from socket import *
import socket
from flask.ext.cors import CORS, cross_origin
import time
# INITIALIZATIONS
noOfNodes = 48
# Initialize all the TCP sockets
tcpClientSockets = dict()
for i in range(48):
tcpClientSockets[i] = socket.socket()
tcpPort = 5000
bufferSizeRecPacket = 102400
nodeIPAddress = '192.168.1.'
startNode = 11
endNode = 58
# Class which provides the web socket communication with the Client/Web-browser
class CORNET_3D_WebSocketConnection:
# Configure the Flask server
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
# Change the configuration such that requests from external IP addresses are accepted
cors = CORS(app, resources={r"/foo": {"origins": "*"}})
app.config['CORS_HEADERS'] = 'Content-Type'
app.debug = True
socketio = SocketIO(app)
def __init__(self):
# Server to run on port 8888
self.socketio.run(self.app, host = '0.0.0.0', port=8888)
@app.route('/', methods=['GET','POST','OPTIONS'])
@cross_origin(origin='*',headers=['Content-Type','Authorization'])
def index():
# TODO: Get the node status for all the nodes
return ''
@socketio.on('nodeID')
def startSpectrum(initParams):
# TODO: Add the client to the list of clients
# TODO: SSH to the node specified
current_client_id = request.environ['REMOTE_ADDR']
print current_client_id
# Extract the transParams
transParams = initParams['transParams']
nodeID = initParams['nodeID']
# Get the IPv4 address for the node
nodeIPv4Address = nodeIPAddress + str(nodeID)
# Validate the IPv4 Address
try:
validate = CORNET_3D_ValidateParameters()
if validate.isIPv4AddressValid(nodeIPv4Address):
# If parameters are valid in the IPv4 address
if validate.isParamsValid(transParams):
try:
# TODO: Add the client IP address to the list of connected clients
time.sleep(1)
tcpClientSockets[nodeID - startNode].close()
spectrumParams = "PARAMS--f:" + str(transParams['f']) + " b:" + str(transParams['b']) + " n:" + str(transParams['n']) + " r:" + str(transParams['r'])
print spectrumParams
try:
print 'Connecting'
print nodeIPv4Address
tcpClientSockets[nodeID - startNode] = socket.socket()
print 'Create Tcp client sockets'
tcpClientSockets[nodeID - startNode].connect((nodeIPv4Address, tcpPort))
print 'Connected'
tcpClientSockets[nodeID - startNode].send(spectrumParams)
print 'Sent spectrum data'
while True:
spectrumData = tcpClientSockets[nodeID - startNode].recv(bufferSizeRecPacket)
tcpClientSockets[nodeID - startNode].send('spectrum..........................................')
emit('time', spectrumData)
except Exception as e:
print "Exception caused in TCP connection -- Start spectrum. Error: ", e
except Exception as e:
print "Exception caused in Validate -- Start spectrum. Error: ", e
else:
emit('error', 'Invalid parameters for the node')
else:
emit('error','Invalid IP address for the node')
except Exception as e:
print "Exception caused in Start Spectrum. Error: ", e
@socketio.on('getMetrics')
def getMetrics(message):
# TODO: Get metrics to be implemented
print 'Get metrics'
@socketio.on('closeSSH')
def closeSSH(nodeID):
# TODO: Remove the client from the list of connected clients
try:
print 'CLOSE SSH'
#tcpClientSockets[int(nodeID) - startNode].send('exit..............................................')
print 'Exit sent'
tcpClientSockets[int(nodeID) - startNode].shutdown(socket.SHUT_RDWR)
except Exception as e:
print "Exception caused in Closing the connection with the client. Error: ", e
@socketio.on('disconnect')
def disconnect(nodeID):
# TODO: Remove the client from the list of connected clients
try:
print 'DISCONNECT'
tcpClientSockets[int(nodeID) - startNode].send('exit..............................................')
tcpClientSockets[nodeID - startNode].close()
except Exception as e:
print "Exception caused in Closing the connection with the client. Error: ", e
@socketio.on('users_req')
def getClientsConnected():
# TODO: Get the clients that are connected to the web socket through web browsers
print 'Users Req'
# Class which validates parameters and IPv4 address
class CORNET_3D_ValidateParameters:
def isIPv4AddressValid(self, ipAddress):
try:
socket.inet_pton(socket.AF_INET, ipAddress)
except AttributeError:
try:
socket.inet_aton(ipAddress)
except socket.error:
return False
return ipAddress.count == 3
except socket.error:
return False
return True
def isParamsValid(self, parameters):
try:
f = int(parameters['f'])
b = int(parameters['b'])
n = int(parameters['n'])
r = int(parameters['r'])
return True
except ValueError:
return False
if __name__ == '__main__':
webServer = CORNET_3D_WebSocketConnection()