Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Socket.io不同时侦听两个连接_Python_Sockets_Flask_Socket.io 1.0 - Fatal编程技术网

Python Socket.io不同时侦听两个连接

Python Socket.io不同时侦听两个连接,python,sockets,flask,socket.io-1.0,Python,Sockets,Flask,Socket.io 1.0,下面是在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 Fl

下面是在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()

如果您正在为服务器使用gevent或eventlet,则需要对标准库进行monkey patch,以确保所有I/O调用都通过绿色线程启用库进行路由。如果您正在为服务器使用gevent或eventlet,则需要对标准库进行monkey patch,确保所有I/O调用都通过绿色线程启用库路由。