def __init__( self, game, addresses, port, versionString, adminPassword ): self.game = game self.versionString = versionString self.shutdownOrder = False self.adminPassword = adminPassword self.rawConnections = [] self.playerCons = [] self.sockets = [] self.updating = {} self.socketsOpened = [] self.listening = False ### open listener sockets for address in addresses: try: socket = SocketType() socket.setblocking(0) socket.bind( ( address, port ) ) socket.listen( 10 ) socket.setblocking( 0 ) print "opened socket on %s:%i" % (address,port) self.sockets.append( socket ) self.socketsOpened.append( address ) self.listening = True tSocket = Thread( name="socket on %s:%i"%(address,port), target=self.threadListener, args=(socket,) ) tSocket.start() except Exception, ex: print "failed to open socket on %s:"%address, ex[1]
def bind(self, socket, address): try: socket.bind(address) self._print("Socket bound...") except Exception, e: print "Error binding to socket" exit(1)
def wait_for_ack(ip=local_ip, port=None, socket_type=zmq.PAIR, **additional_info): socket = ctx.socket(socket_type) poller = zmq.Poller() poller.register(socket, zmq.POLLIN) if not ip: ip = get_local_ip() if not port: port = socket.bind_to_random_port('tcp://%s' % ip) else: socket.bind('tcp://%s:%s' % (ip, port)) def _(timeout=3 * 1000): if poller.poll(timeout): m = socket.recv_json() socket.close() assert 'act' in m assert 'ack' == m['act'] for k, v in additional_info.items(): if k not in m: return False if v != m[k]: return False return True return port, _
def threaded_function(self): context = zmq.Context() socket = context.socket(zmq.REP) socket.bind(self.url) while True: message = socket.recv() self.queue.put(message) socket.send_string("Ok")
def _cmd_worker(self): context = zmq.Context() socket = context.socket(zmq.REP) socket.bind(self.cmd_address) while True: cmd = socket.recv_string() res = self._handle_cmd(cmd) socket.send_string(res)
def start(self, testing=False): """Primary reactor loop. This handles standard signals as interpreted by Python, such as Ctrl+C. """ log.info("Starting up.") socket = self.socket = self._socket() socket.bind(self.address) socket.listen(self.pool) if self.fork is None: self.fork = self.processors() elif self.fork < 1: self.fork = min(1, self.processors() + self.fork) # Single-process operation. if self.fork == 1: self.serve(testing=testing) return # Multi-process operation. log.info("Pre-forking %d processes from PID %d.", self.fork, os.getpid()) for i in range(self.fork): if os.fork() == 0: try: random.seed(long(hexlify(os.urandom(16)), 16)) except NotImplementedError: random.seed(int(time.time() * 1000) ^ os.getpid()) self.serve(False) return try: os.waitpid(-1, 0) except OSError: pass except KeyboardInterrupt: log.info("Recieved Control+C.") except SystemExit: log.info("Recieved SystemExit.") raise except: log.exception("Unknown server error.") raise self.stop() return
def zmq_listener(): context = zmq.Context() socket = context.socket(zmq.PULL) socket.bind(ZMQ_SUB_LISTEN_ADDR) while True: msg = socket.recv() if '\n' in msg or '\r' in msg: continue send_line(msg.decode('utf-8'))
def create_socket(socktype, endpoints,flag): socket = zmq.Socket(zmq.Context.instance(), socktype) socket.setsockopt(zmq.LINGER, 0) for endpoint in endpoints: if flag==1: socket.bind(endpoint) else: socket.connect(endpoint) return socket
def run(socket): socket.bind((address, port)) try: socket.connect((self.DEFAULT_SRC_ADDRESS, self.DEFAULT_SRC_PORT)) self.end_event.wait() socket.free() except Exception, e: traceback.print_exc(e) self.network.close()
def bind_port(socket, ip, port): """ Binds the specified ZMQ socket. If the port is zero, a random port is chosen. Returns the port that was bound. """ connection = 'tcp://%s' % ip if port <= 0: port = socket.bind_to_random_port(connection) else: connection += ':%i' % port socket.bind(connection) return port
def run(socket): socket.bind((address, port)) socket.listen() launched_event.set() try: socket.accept(timeout=self.DEFAULT_TIMEOUT) self.end_event.wait() socket.free() except Exception, e: traceback.print_exc(e) self.network.close()
def start_listener(port): context = zmq.Context() socket = context.socket(zmq.REP) socket.bind("tcp://*:{}".format(port)) while True: # Wait for next request from client message = socket.recv() socket.send("") if message == "Done!": break print ("Received message: %s" % message)
def start(self): socket = self.ctx.socket(zmq.REP) service_address = self.my_conf.get("Service","service_default_bind_address") log.debug("Serving at %s"%service_address) socket.bind(service_address) log.debug("Start serving") while True: message = socket.recv() log.debug("Message received: %s"%message) command = self.my_conf.get("Service","command") command_list = command.split(" ") log.debug("Execution of: %s"%command_list) cmd = subprocess.Popen(command_list,stdout=subprocess.PIPE) socket.send(b"|%s|"%cmd.stdout.read())
def main(): print("[HTT] Start server") socket = HTTPSocket() print("[HTT] bind 8080") socket.bind(8080) # get connection conn, addr = socket.accept() while conn is not None: thread = HTTPMainThread(conn, 1024, addr[0], addr[1]) thread.run() conn, addr = socket.accept()
def serverlisten(self,socket,port,time): host='' try: socket.bind((host,port)) except: print('bind failed, error code'+str(msg[0])+'Message: '+msg[1]) sys.exit() socket.listen(time) while True: conn,addr=socket.accept() print('conneted with '+addr[0]+':'+str(addr[1])) data=conn.recv(1024) result1=data.decode("utf-8") conn.close() socket.close() break return result1
def accept_file(): host= ni.ifaddresses('eth1')[2][0]['addr'] port = 10018 socket.bind((host,port)) socket.listen(5) conn, addr = socket.accept() print 'connecting from:',addr buffer = conn.recv(1024) global full_path full_path = buffer.split('\0')[0] print full_path global name temp = full_path.split('/',2)[2] name = temp.split('.',2)[0] print name if True == os.path.isfile(full_path): print 'file(%s) is already exist'% full_path del_op= 'rm '+ full_path os.system(del_op) dir = full_path.split('.')[0] if True == os.path.exists(dir): print "directory already exist %s"% dir delete_con = 'docker rm -f '+name+ ' >/dev/null 2>&1' print delete_con os.system(delete_con) del_dir = 'rm -fr '+ dir os.system(del_dir) conn.send('ready') #conn, addr = socket.accept() fname = open(full_path, 'wb') while True: strng = conn.recv(4096) if not strng: fname.close() conn.close() print "recv file success" break else: fname.write(strng)
def ssl_listener(address, certificate, private_key): """Listen on the given (ip, port) *address* with a TCP socket that can do SSL. Primarily useful for unit tests, don't use in production. *certificate* and *private_key* should be the filenames of the appropriate certificate and private key files to use with the SSL socket. Returns a socket object on which one should call ``accept()`` to accept a connection on the newly bound socket. """ from eventlet import util import socket socket = util.wrap_ssl(socket.socket(), certificate, private_key, True) socket.bind(address) socket.listen(50) return socket
def localization_server(ip,port): context = zmq.Context() socket = context.socket(zmq.REP) socket.bind(("tcp://*:%d" % port)) dummy = { 'pos' : {'x':'100','y':'100','z':'100'}, 'orient': {'w':'1','x':'0','y':'0','z':'0'}}; while True: # Wait for next request from client message = socket.recv() print("Received request: %s" % message) # Do some 'work' time.sleep(0.050) # Send reply back to client socket.send(json.dumps(dummy)) print "quitting ... "
def MakeSocket(self, context, url = None, type = None, bind = None, options = None, pre_delay = None, post_delay = None): """Create the socket. Arguments take precendence over their corresponding object attributes. """ if type == None: type = self.type if url == None: url = self.url if bind == None: bind = self.bind if options == None: options = {} if self.options != None: if options == None: options = self.options else: options = dict(options.items() + self.options.items()) if pre_delay == None: pre_delay = self.pre_delay if post_delay == None: post_delay = self.post_delay assert type is not None socket = context.socket(type) for k, v in options.items(): socket.setsockopt(k, v) if pre_delay != None: time.sleep(pre_delay) assert url is not None if bind: logging.info("Binding %s socket to %s with context %s" % ( SocketTypeToString(type), url, hash(context))) socket.bind(url) else: logging.info("Connecting %s socket to %s with context %s" % ( SocketTypeToString(type), url, hash(context))) socket.connect(url) if post_delay != None: time.sleep(post_delay) return socket
def Main(): socket = socket.socket() host = '0.0.0.0' port = 5001 socket.bind((host,port)) socket.listen(10) c, addr = socket.accept() while 1: c.send("StepsS:") stepsS = c.recv(1024) c.send("StepsT:") stepsT = c.recv(1024) if stepS > 0: moveforwardS(stepsS) else: movebackwardS(-stepsS) if stepsT > 0: moveforwardT(stepsT) else: movebackwardT(stepsT)
def main(): sim = Simulation(SpeedLimit=0.5, RandomChanges=10) # instantiate the simulation wrapper # Setup comm sockets context = zmq.Context() socket = context.socket(zmq.PUB) # publish to all upstreams services socket.bind("tcp://127.0.0.1:5550") # localhost only, no encryption # Main Loop while True: # -------------------------------------------------------------------------- # Calculate next round # -------------------------------------------------------------------------- sim.Solve() # TODO destabilization code - restore? # -------------------------------------------------------------------------- # Send state to visualization/freq model # -------------------------------------------------------------------------- socket.send_json(sim.Output())
def run(self): context = zmq.Context() socket = context.socket(zmq.REP) socket.bind("tcp://*:%d" % self.port) poller = zmq.Poller() poller.register(socket, zmq.POLLIN) while not self.stopped(): # timeout so we can free the socket and quit the program # if necessary; in ms socks = dict(poller.poll(timeout=100)) if socket in socks and socks[socket] == zmq.POLLIN: print("got dns question") msg = socket.recv() if msg in self.database.domains: domain = self.database.domains[msg] socket.send("%s %d" % (domain.ip, domain.ttl)) else: socket.send("0.0.0.0 %d" % default_ttl)
def run(self): self.socket=socket.socket() self.socket=socket.bind((self.ip,self.port)) self.socket.listen(4) while True: gelen_data=self.socket.recv(1024) mesaj=self.parser(gelen_data) if gelen_data != "": print "gelen_data:"+gelen_data self.socket.close()
import socket, threading socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = '' socket.bind((host, 8000)) socket.listen(20) players = [] lobby = [] # wrapper function read from socket def readnbytes(socket, n): s = '' count = 0 while count < n: temp = socket.recv(1) s = s + temp count += 1 return s # wrapper function to write to socket def sendnbytes(socket, msg, n): sent = 0 while sent < n: temp = socket.send(msg[sent:]) sent += temp #thread that handles communication with one of the players class Player(threading.Thread): def __init__(self, con, username):
#!/usr/bin/env python # GIT test import test import socket import tensorflow as tf import Numpy_test host = '' port = 50000 backlog = 5 size = 1024 socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.bind((host, port)) socket.listen(backlog) test.test_func() # prints "Hello!" Numpy_test.numpy_func() # print("Server Started") while True: connection = None try: connection, address = socket.accept() print("Unity Connected.") # connection.send("First call from Python\n") while True: data = connection.recv(size).decode() if data:
if __name__ == "__main__": yy = atpic.log.setname(xx, 'main') # run as user www-data os.setuid(33) # Set the signal handler and a 5-second alarm signal.signal(signal.SIGTERM, handler) atpic.log.debug(yy, "daemon started") p1 = start_exif() # atpic.log.debug(yy,dir(p1)) context = zmq.Context() socket = context.socket(zmq.PULL) socket.bind("tcp://127.0.0.1:5000") counter = 0 ittooks = [] while True: try: # receive the message msg = socket.recv() counter += 1 atpic.log.debug(yy, "Total messages recieved: {0}".format(counter)) receivedData = msg atpic.log.debug(yy, "receivedData", receivedData) time1 = time.time() p1.stdin.write(b'-X\n') p1.stdin.write(b'-long\n') p1.stdin.write(receivedData + b'\n') # the filename as bytes with \n
import socket from joystick import Joystick socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.bind(('', 15555)) socket.listen(1) client, address = socket.accept() print("{} connected".format( address ) ) with Joystick('/dev/ttyUSB2', 57600) as joy: for m in joy: print(m) client.send(m) client.close() socket.close() print("Close")
import socket socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.bind(('localhost', 15555)) while True: socket.listen(5) client, address = socket.accept() print("{} connected".format(address)) response = client.recv(255) if response != "": print(response) print("Close") client.close() stock.close()
import socket socket = socket.socket() socket.bind(('127.0.0.1', 8080)) socket.listen(5) while True: conn, addr = socket.accept() data = conn.recv(8096) print(data) conn.send(b'HTTP/1.1 200 OK\r\n\r\n') conn.send(b'123') conn.close()
import os import serial import time import socket from serial.tools import list_ports UDP_LOCAL = "127.0.0.1" UDP_REMOTE = "127.0.0.1" UDP_SEND = 5005 UDP_RECEIVE = 5006 socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) socket.bind((UDP_LOCAL, UDP_RECEIVE)) serbaud = 9600 sertimeout = 3 RoverDrivePortString = "ID: MainDrive" RoverDrivePort = "" def list_serialPorts(): for port in list_ports.comports(): yield port[0] def get_controlPort(checkString): for port in list(list_serialPorts()): try: ser = serial.Serial(port, serbaud, timeout=sertimeout) multilinecheck = [] for i in range(0, 2):
def check_channel_request(self, kind, chanid): if kind == 'session': return paramiko.OPEN_SUCCEEDED return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED def check_auth_password(self, username, password): if (username == 'tim') and (password == 'sekret'): return paramiko.AUTH_SUCCESSFUL if __name__ == '__main__': server = '192.168.1.207' ssh_port = 2222 try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) socket.bind((server, ssh_port)) sock.listen(100) print('[+] Listening for connection ...') client, addr = sock.accept() except Exception as e: print('[-] Listen failed: ' + str(e)) sys.exit(1) else: print('[+] Got a connection!', client, addr) bhSession = paramiko.Transport(client) bhSession.add_server_key(HOSTKEY) server = Server() bhSession.start_server(server=server) chan = bhSession.accept(20)
import socket # Import socket module B_host = '127.0.0.1' # Get local machine name B_port = 50000 # Reserve a port for your service. A_port = 50001 # Reserve a port for your service. A_host = '127.0.0.1' socket = socket.socket() # Create a socket object with open('received_tcp.jpg', 'wb') as f: print('file opened') socket.bind((B_host, B_port)) # Bind to the port socket.listen(5) # Now wait for client connection. while True: conn, addr = socket.accept() # Establish connection with client. print('Got connection from', addr) data = conn.recv(1024) #print('data=%s', (data)) if not data: break # write data to a file f.write(data) f.close() print('Successfully get the file') socket.close() print('connection closed')
def server(): while True: # time.sleep(2) try: context_rep = zmq.Context() socket = context_rep.socket(zmq.REP) socket.bind("tcp://*:8002") try: message = socket.recv_string() print(message) l = message.split("_") if l[0] == "p": if l[1] == yo: # aqui se devuelve enviando el puerto del sevicio hasta llegar a cliente print(l) ruta = l[5] # se extrae el diccionario_string ruta # se convierte a diccionario ruta_dic = json.loads(ruta) # agrego mi servicio/nodo a la ruta ruta_dic[yo] = {"ip": nombre_equipo, "puerto": mi_port} keys = [] # se guardaran las keys del diccionario ruta # se extraen todas las keys (para saber cuantos nodos hay en la ruta) for key in ruta_dic: keys.append(key) # se agrega el dato ruta actualizado a la lista #l[5] = json.dumps(ruta_dic) print("llaves de ruta: ", keys) # si estamos ubicados en el ultimo nodo mas cercano al cliente cambiamos el token que esta al inicio del mensaje # lo sabemos si en ruta solo quedan dos nodos: el cliente y el que tiene el servicio # print(directorio) # traer la seccion de ruta para analizar cual fue el ultimo nodo agregado # enviar el puerto y el host al ultimo nodo # eliminar el ultimo nodo de la ruta #a = directorio.get(l[4]) a = ruta_dic.get(keys[-2]) # eliminar penultimo nodo de ruta (el ultimo contiene la direccion del servicio buscado) if len(keys) > 2: ruta_dic.pop(keys[-2]) l[5] = json.dumps(ruta_dic) l[0] = "s" nuevo_msm = '_'.join(l) print("nuevo mensaje:", nuevo_msm) host = a["ip"] puerto = a["puerto"] print("host y puerto", host, puerto) context_respuesta = zmq.Context() socket_respuesta = context_respuesta.socket(zmq.REQ) socket_respuesta.connect("tcp://" + host + ":" + puerto) socket_respuesta.send_string(nuevo_msm) else: cliente = l[4] ruta_str = l[5] # string de ruta ruta_dic = json.loads(ruta_str) # diccionario de ruta print(ruta_dic) ruta_dic[yo] = {"ip": nombre_equipo, "puerto": mi_port} ruta_str = json.dumps(ruta_dic) l[5] = ruta_str nuevo_msm = '_'.join(l) keys = [] # se guardaran las keys del diccionario ruta # se extraen todas las keys (para saber cuantos nodos hay en la ruta) for key in ruta_dic: keys.append(key) # tenemos que verificar no replicar el mensaje a los nodos que ya estan dentro de ruta for key in directorio: if key != yo and key != cliente and key not in keys: info = directorio.get(key) print(info) context_replicar = zmq.Context() socket_replicar = context_replicar.socket( zmq.REQ) socket_replicar.connect("tcp://" + info['ip'] + ":" + info['puerto']) socket_replicar.send_string(nuevo_msm) elif l[0] == "r": msm_c = l[1] # operador a = directorio.get(msm_c) if a == None: adicionar(l) # print(directorio) else: pass # recibir mensaje de confirmacion (servicio encontrado) elif l[0] == "s": # si queda un solo elemento en ruta: conectar directamente # sino seguir pasando el mensaje al penultimo nodo de ruta ruta_str = l[5] ruta_dic = json.loads(ruta_str) keys = [] for key in ruta_dic: keys.append(key) print("estas son las keys: ", keys) if len(keys) == 2: # conectarse directamente aux = ruta_dic.get(l[1]) # "+" host = aux["ip"] port = aux["puerto"] ruta_dic.pop(l[1]) l[5] = json.dumps(ruta_dic) nuevo_msm = '_'.join(l) context_servicio = zmq.Context() socket = context_servicio.socket(zmq.REQ) socket.connect("tcp://" + host + ":" + port) socket.send_string(nuevo_msm) # el servidor recibe conexion directa de elif len(keys) == 1: print("entro correctamente felicitaciones !!!") respuesta = int(l[2]) - int(l[3]) print(respuesta) respuesta = "e"+"_" + \ l[1]+"_"+l[2]+"_"+l[3]+"_" + \ str(respuesta) # "resultado_-_2_3_1" print(respuesta) aux = ruta_dic.get(l[4]) # "+" host = aux.get("ip") port = aux.get("puerto") print("aux", aux) print("host", host) print("puerto", port) context_servicio = zmq.Context() socket_res = context_servicio.socket(zmq.REQ) # socket_res.connect("tcp://"+host+":"+port) socket_res.connect("tcp://" + host + ":" + port) socket_res.send_string(respuesta) else: aux = ruta_dic.get(keys[-2]) # [+,-,/] host = aux["ip"] port = aux["puerto"] ruta_dic.pop(keys[-2]) # [+,/] context_servicio = zmq.Context() socket = context_servicio.socket(zmq.REQ) socket.connect("tcp://" + host + ":" + port) socket.send_string(mensaje) elif l[0] == "e": print("entro a resultado") # "resultado_-_2_3_1" print(l) print(str(l[2]) + str(l[1]) + str(l[3]) + ": " + str(l[4])) elif l[0] == "resultado": # "resultado_-_2_3_1" print(l[2] + l[1] + l[3] + ": " + l[4]) except: pass except: pass
import socket HOST = "127.0.0.1" PORT = 3000 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as socket: socket.bind((HOST, PORT)) print("SOCKET BINDED SUCCESFULLY WITH THE SERVER") socket.listen() print("Socket status ====== listening") connection, address = socket.accept() with connection: #the with statement is like try and finally only + it will even close the connection once code is executed completely print(address) while 1: data = connection.recv(1024) if not data: print( data ) # empty bytes object is sent when a connection is closed from client side print("Disconnected") break else: connection.sendall(data)
def runmaster(nClients): setupDict = yaml.load(open('smalldata_plot.yml', 'r')) master_port = setupDict['master']['port'] context = zmq.Context() socket = context.socket(zmq.PUB) socket.bind("tcp://*:%s" % master_port) myDict = {'runNumber': -1} hutches = ['amo', 'sxr', 'xpp', 'xcs', 'mfx', 'cxi', 'mec'] hutch = None print('master_PUB pre pre hostname') import socket as skt hostname = skt.gethostname() print('master_PUB post pre hostname') #hostname=socket.gethostname() #this is a problem now - not interactively...WHY? #print('master_PUB post hostname') for thisHutch in hutches: if hostname.find(thisHutch) >= 0: hutch = thisHutch.upper() if hutch is None: #then check current path path = os.getcwd() for thisHutch in hutches: if path.find(thisHutch) >= 0: hutch = thisHutch.upper() if hutch is None: print( 'cannot figure out which hutch we are in to use. resetting at end of run will not work' ) #main "thread" to get the MPI data and append it to the dict. nDataReceived = 0 print( 'About to start the while loop for the master process w/ %d clients' % nClients) while nClients > 0: print('MASTER got data: ', nDataReceived) nDataReceived += 1 ##get current run number & reset if new. Put into thread? ##here, I'm resetting the master dict on a new run. For now, this is not exactly how this should run. ##need to maybe use a deque for the jet tracking? Figure out much later how to combine... #if hutch is not None and nDataReceived%(size-1)==(size-2): # lastRun = RegDB.experiment_info.experiment_runs(hutch)[-1]['num'] # #if the run number has changed, reset the master dictionary & set the new run number. # if lastRun != myDict['runNumber']: # print('Reset master dict, new run number: %d'%lastRun) # myDict.clear() # myDict['runNumber']=lastRun # Remove client if the run ended md = mpidata() md.recv() ##ideally, there is a reset option from the bokeh server, but we can make this ##optional & reset on run boundaries instead/in addition. if md.small.endrun: #what if going from just running to recording? print('ENDRUN!') #nClients -= 1 #No... myDict.clear() myDict['runNumber'] = lastRun else: print('DEBUG: master: ', md.nEvts) #append the lists in the dictionary we got from the clients to a big master dict. for mds in md.small.arrayinfolist: #print 'mds name: ',mds.name if mds.name not in myDict.keys(): myDict[mds.name] = getattr(md, mds.name) else: myDict[mds.name] = np.append(myDict[mds.name], getattr(md, mds.name), axis=0) #check if dict is aligned for mds in md.small.arrayinfolist: if mds.name == 'nEvts': continue if mds.name == 'send_timeStamp': continue if myDict[mds.name].shape[0] != myDict['event_time'].shape[0]: print('We are out of alignment for %s ' % mds.name, myDict[mds.name].shape[0], myDict['event_time'].shape[0]) #md.addarray('evt_ts',np.array(evt_ts)) evt_ts_str = '%.4f' % (md.send_timeStamp[0] + md.send_timeStamp[1] / 1e9) #here we will send the dict (or whatever we make this here) to the plots. print('master data: ', myDict.keys()) print('master has events: ', myDict['lightStatus__xray'].shape) # # this is if we send data off via ZMQ. # #print("smallData master received request: ", message) #if len(dict_to_send.keys())>0: # print("smallData master will send : ", dict_to_send['lightStatus__xray'].shape) #else: # print("we have an empty dictionary right now....") socket.send_pyobj(myDict)
import socket # Create a TCP/IP socket socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Create server address server_address = ('localhost', 2001) print('Server waiting for connection') # Bind socket to the server_address socket.bind(server_address) # the math function def math(message): # split message to remove the comms ',' message = message.split(',') # assign the values of the operation and variables operation = message[0] first_variable = int(message[1]) second_variable = int(message[2]) # perform operation if operation == '1': return first_variable + second_variable elif operation == '2': return first_variable - second_variable elif operation == '3': return first_variable * second_variable elif operation == '4':
def launch_server(): port = "5000" context = zmq.Context() socket = context.socket(zmq.PUB) socket.bind("tcp://*:%s" % port) maxlen = 1000000 # Get data beam = FakeBeam() peak_8 = deque(maxlen=maxlen) peak_8_TS = deque(maxlen=maxlen) peak_9 = deque(maxlen=maxlen) peak_9_TS = deque(maxlen=maxlen) peak_10 = deque(maxlen=maxlen) peak_10_TS = deque(maxlen=maxlen) peak_11 = deque(maxlen=maxlen) peak_11_TS = deque(maxlen=maxlen) peak_12 = deque(maxlen=maxlen) peak_12_TS = deque(maxlen=maxlen) peak_13 = deque(maxlen=maxlen) peak_13_TS = deque(maxlen=maxlen) peak_14 = deque(maxlen=maxlen) peak_14_TS = deque(maxlen=maxlen) peak_15 = deque(maxlen=maxlen) peak_15_TS = deque(maxlen=maxlen) # Subscribe to devices beam.peak_8.subscribe(partial(new_data, in_value=peak_8, in_time=peak_8_TS)) beam.peak_9.subscribe(partial(new_data, in_value=peak_9, in_time=peak_9_TS)) beam.peak_10.subscribe( partial(new_data, in_value=peak_10, in_time=peak_10_TS)) beam.peak_11.subscribe( partial(new_data, in_value=peak_11, in_time=peak_11_TS)) beam.peak_12.subscribe( partial(new_data, in_value=peak_12, in_time=peak_12_TS)) beam.peak_13.subscribe( partial(new_data, in_value=peak_13, in_time=peak_13_TS)) beam.peak_14.subscribe( partial(new_data, in_value=peak_14, in_time=peak_14_TS)) beam.peak_15.subscribe( partial(new_data, in_value=peak_15, in_time=peak_15_TS)) peakDict = { 'peak_8': peak_8, 'peak_9': peak_9, 'peak_10': peak_10, 'peak_11': peak_11, 'peak_12': peak_12, 'peak_13': peak_13, 'peak_14': peak_14, 'peak_15': peak_15 } peakTSDict = { 'peak_8_TS': peak_8_TS, 'peak_9_TS': peak_9_TS, 'peak_10_TS': peak_10_TS, 'peak_11_TS': peak_11_TS, 'peak_12_TS': peak_12_TS, 'peak_13_TS': peak_13_TS, 'peak_14_TS': peak_14_TS, 'peak_15_TS': peak_15_TS } data = {'peakDict': peakDict, 'peakTSDict': peakTSDict} # Send data a half second intervals while True: socket.send_pyobj(data) print(len(data['peakDict']['peak_8'])) time.sleep(1)
winner=gameOver() if(winner==gamers[0]): #on envoie le résultat de la partie au joueur message = str(WINNER).encode() gamers[0].send(message) message = str(LOOSER).encode() gamers[1].send(message) else: message = str(WINNER).encode() gamers[1].send(message) message = str(LOOSER).encode() gamers[0].send(message) socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #on ouvre le serveur socket.bind(('', port)) socket.listen(5) print("Démarrage serveur : port : {}".format(port)) threadgame = threading.Thread(None, game,None, (), {}) #on crée puis on démarre une thread qui va gérer la partie threadgame.start() while 1: #on sauvegarde les connexions client, address = socket.accept() nb_client = nb_client+1 if(nb_client==1): gamers.append(client) if(nb_client==2): gamers.append(client) if(nb_client>2): spectator.append(client)
ts2_hostname = sys.argv[4] addr2 = socket.gethostbyname(ts2_hostname) server_binding = (addr2, int(sys.argv[5])) socket2.connect(server_binding) # _____ CLIENT CONNECTION _____ try: socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print "[AS]: Server socket created" except socket.error as err: print '[AS]: socket open error: {}\n'.format(err) exit() server_binding = ('', int(sys.argv[1])) socket.bind(server_binding) socket.listen(1) socketC, add = socket.accept() print "[AS]: Connection received from: {}".format(add) while True: # Receive challenge and digest from client request = socketC.recv(200).decode('utf-8') challenge, digest = request.split(" ") print "[AS]: Received challenge + digest: " + challenge + ", " + digest # Send challenge to ts socket1.send(challenge.encode('utf-8')) print "[AS]: Sent 1/2" socket2.send(challenge.encode('utf-8')) print "[AS]: Sent 2/2"
def start(self): """start the listener""" # set up the socket while True: # get the next task #print ">> DBG about to get task" # don't let the result queue get too big! if int(self.resultQueue.qsize()) > self.resQUpperLimit: while int(self.resultQueue.qsize()) > self.resQLowerLimit: time.sleep(10) task = self.taskQueue.get(block=True, timeout=None) if task == None: # poison pill #print ">> DBG Last task" break #print ">> DBG got task: %d" % task.id # configure zmq to listen for the result socket_OK = False context = zmq.Context() socket = context.socket(zmq.REP) while not socket_OK: try: socket.bind("tcp://*:%s" % self.port) socket_OK = True except zmq.ZMQError: #print sys.exc_info()[0], "Job: %d" % task.id time.sleep(1) # set the worker going ret_str, sge_script_fn = self.queueManager.makeSgeScript(self.sgeBaseDir, self.workingDir, task.id, task.gPath1, task.gPath2, task.gid1, task.gid2, task.ani, "tcp://%s:%d" % (self.ip, self.port) ) exit_status = self.queueManager.lodgeJob(ret_str, sge_script_fn) if exit_status == 0: # TO DO: send the deets of this job off to an external management thread which # monitors the queue to make sure the job isn't just dropped. If it is then is can send # a "DIE" signal to this listener # wait for result from worker and decode (blocking) #print ">> DBG waiting for worker: %d" % task.id result = jp.decode(socket.recv().decode("zlib")) # check to see we've not been told to die if result == "DIE": # we abandon the worker and simply exit return # check to see that there was no issue running the worker # basically, check to see that the last item in the result array is # actually a hit if len(result) > 3: # there is something on the end of this array if result[-2] == "ERROR": # something went wrong. Print it out! # TODO use logging module print self.id, self.gPath1, self.gPath2 print result[-1] result[1] = float(result[1])/1000. # place the result on the result queue self.resultQueue.put(result) #print ">> DBG %d The length of result queue is %d" % (task.id,int(self.resultQueue.qsize())) # tell the worker to exit socket.send("DIE") else: print " OH NO! EXIT STATUS == %d : %d" % (exit_status, task.id) time.sleep(8)
def report(str): stdscr.addstr(0, 0, str) stdscr.refresh() if __name__ == "__main__": stdscr = curses.initscr() curses.noecho() curses.cbreak() local_ip = '' local_port = 8890 socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # socket for sending cmd socket.bind((local_ip, local_port)) tello_ip = '192.168.10.1' tello_port = 8889 tello_adderss = (tello_ip, tello_port) socket.sendto('command'.encode('utf-8'), tello_adderss) try: index = 0 while True: index += 1 response, ip = socket.recvfrom(1024) if response == 'ok': continue out = response.replace(';', ';\n')
sendPacket.ref_id = 0x808a8c2c ''' sendPacket.ref_timestamp = recvTimestamp-5 sendPacket.SetOriginTimeStamp(timeStamp_high,timeStamp_low) sendPacket.recv_timestamp = recvTimestamp sendPacket.tx_timestamp = system_to_ntp_time(time.time()) socket.sendto(sendPacket.to_data(),addr) print "Sended to %s:%d" % (addr[0],addr[1]) except Queue.Empty: continue listenIp = "0.0.0.0" listenPort = 123 socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) socket.bind((listenIp,listenPort)) print "local socket: ", socket.getsockname(); recvThread = RecvThread(socket) recvThread.start() workThread = WorkThread(socket) workThread.start() while True: try: time.sleep(0.5) except KeyboardInterrupt: print "Exiting..." stopFlag = True recvThread.join() workThread.join() #socket.close()
import struct import socket import time from threading import Thread buffer = [] message = struct.pack("!BB", 0, 255) for i in range(36): message += struct.pack("!BBB", 255, 255, 255) socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) socket.bind(("", 0)) def recv_thread(): global socket while True: msg, addr = socket.recvfrom(1024) print(msg, addr) Thread(target=recv_thread).start() while True: socket.sendto(message, ("192.168.1.2", 8888)) time.sleep(5) print("sending")
#!/usr/bin/python __author__ = "F3n3s7ra" # Exhausts all UDP ports so a DNS request will fail and a fallback to NBNS will occur import socket socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) hostname = 'localhost' for port in range(0, 65536) socket.bind(hostname, port)
if command.endswith(AtHomeProtocol['end_of_line']): command = command[0:-2] if command in AtHomeCommands: AtHomeCommands[command](file) else: command = "" raise NameError('[Unknown Command] %s' % command) command = "" except EOFError: file.close() socket.close() return except Exception as e: print('[Exception] %s' % e, file=sys.stderr) if __name__ == "__main__": socket = socket.socket() socket.bind(('0.0.0.0', 4444)) socket.listen(5) while True: conn, address = socket.accept() if conn is not None: print('Accepted connection', file=sys.stderr) if fork() == 0: listen_on_socket(conn, address) sys.exit(0) else: conn.close() sleep(0.001)
import socket from socket import * from math import * socket = "abc" server_socket = socket.socket(AF_INET, SOCK_STREAM) # tcp socket 服务端 socket = socket() socket.bind() socket.listen() cli_socket = socket.accept() while True: p = Process(target=fun, args=()) p.start() cli_socket.close() def fun(cli_socket): # 接收数据 # request_data = recv() # print(request_data) # 解析HTTP报文数据 request_data # 提取请求方式 # 提取请求路径path HTML_ROOT_DIR= "./html" path = /index.html /login.html try: file = open(HTML_ROOT_DIR + "index.html")
#!/usr/bin/env python3 import socket, struct from math import pi from time import sleep, time socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.bind(('localhost', 2080)) socket.listen(1) client, address = socket.accept() client.send(b"\n") print('time,type,latitude,longitude,heading,team,objid') def receivedEnd(t): print(f'{t},END of frame,,,,,') def receivedAnt(t, latitude, longitude, heading, team, objid): print(f'{t},ANT,{latitude},{longitude},{heading},{team},{objid}') def receivedFood(t, latitude, longitude, team, objid): print(f'{t},FOOD,{latitude},{longitude},0,{team},{objid}') def receivedNest(t, latitude, longitude, team, objid): print(f'{t},NEST,{latitude},{longitude},0,{team},{objid}')
import serial import socket socket = socket.socket() print("Socket successfully created") port = 12345 socket.bind(('0.0.0.0', 12345)) print("socket binded to %s" % (port)) socket.listen(1) # Wait for a connection print('waiting for a connection') connection, client_address = socket.accept() print('connection from', client_address) from time import sleep import sys import time import subprocess from math import * serialPortWorks = True users = { 'Pi': ['/dev/ttyUSB0'], 'aaron': ['COM6', 'COM3', 'COM7', 'COM4', 'COM10'] } ser = None f = None f1 = None ####Array Denotation(Real time) ###Gyroscope ##Gx=0 ##Gy=1 ##Gz=2
import socket # definisikan IP untuk binding IP = '172.20.10.2' # definisikan port untuk binding PORT = 5004 # definisikan ukuran buffer untuk menerima pesan BUFFER_SIZE = 1024 # buat socket (bertipe UDP atau TCP?) socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # lakukan binding ke IP dan port socket.bind((IP, PORT)) # lakukan listen socket.listen() # siap menerima koneksi c, addr = socket.accept() # buka file bernama "file_didownload.txt # masih hard code, file harus ada dalam folder yang sama dengan script python f = open('tes.jpeg', 'rb') try: # baca file tersebut sebesar buffer byte = f.read(BUFFER_SIZE)
import socket import sys def createMsg(msg): return msg + '#' SERVER_IP = 'localhost' SERVER_PORT = 5678 BUFFER_SIZE = 1024 TIME_OUT = 10 # 10 seconds ans = "answer" socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.bind((SERVER_IP, SERVER_PORT)) print ('server started') while True: try: socket.listen(1) conn, addr = socket.accept() conn.settimeout(TIME_OUT) question1 = '' for i in range (10): print("connection accepted3") question1 = str( conn.recv(BUFFER_SIZE) ) print("connection accepted4") while not '#' in question1: question1 = str( conn.recv(BUFFER_SIZE) )
#!/usr/bin/python3 # coding: utf-8 import socket,select,threading socket = socket.socket(socket.AF_INET6,socket.SOCK_DGRAM) socket.bind (('', 7777)) while True: data_byte,adress=socket.recvfrom(1500) socket.sendto(data_byte,adress)
import socket #import sys import os import ntpath #from _thread import start_new_thread HOST = '' # server name goes in here PORT = 4444 def path_leaf(path): head, tail = ntpath.split(path) return tail or ntpath.basename(head) socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.bind((HOST, PORT)) socket.listen(10) logged_user = '' # def clientthread(conn): logged_user = '' while True: conn, addr = socket.accept() print ('New client connected ..') #start_new_thread(clientthread, (conn,)) reqCommand = conn.recv(1024).decode('utf-8') print ('Client> %s.' %reqCommand) if (reqCommand == 'out'): print('User %s logged out.' %logged_user) logged_user = '' #break
return hour, minutes, seconds def log(*args): t = current_time(start_time) print("%02d:%02d:%02.3f -" % (t[0], t[1], t[2]), ' '.join(map(str, args))) ip = "0.0.0.0" # 0.0.0.0 will make the server accessable on all network interfaces (wifi and ethernet) port = 2442 # Port to run server on start_time = time.time() # Record start time for logging socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Setup UDP Communication socket.bind((ip, port)) print("Bound to IP: ", ip, "\n\t Port:", port) print("\nServer running!") #ITERATABLE DICTIONARY OF DATA FOR CLIENT TO REQUEST #currently contains all the frame positions, will update with vectors to define rotated coordinate frames at each #swag.enlarge() data = { "ref": 1, "t01": 2, "t02": 3, "t03": 4, "t04": 5, "ee": 6, "d1": 7,
def rib_global(port, nb_bits_nexthop, dirname, socket_rib_name): import socket try: os.nice(-20) except OSError: rib_logger.info('Cannot change the nice.') rib_global_socket_address = '/tmp/'+socket_rib_name # Make sure the socket does not already exist try: os.unlink(rib_global_socket_address) except OSError: if os.path.exists(rib_global_socket_address): raise socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) socket.bind(rib_global_socket_address) socket.listen(5) # Exit properly when receiving SIGINT def signal_handler(signal, frame): rib_logger.info('Received SIGTERM. Exiting.') # Deleting all the backup flows for ts, f in OFFlowsQueue: with open('deleted_rules', 'a') as fd_del: fd_del.write(f+'\n') os.system('ovs-ofctl del-flows s1 '+f) socket.close() sys.exit(0) signal.signal(signal.SIGTERM, signal_handler) def exit_handler(): socket.close() atexit.register(exit_handler) # The Global RIB rib_global = RIBGlobal() # The virtual nexthops handler vnh = VirtualNextHops(rib_global, nb_bits_nexthop, logger=rib_logger) OFFlowsQueue = FlowsQueue(60*5) # Backup rules deleted after 5 minutes sock_list = [socket] data_dic = {} while True: inready, outready, excepready = select.select (sock_list, [], []) for sock in inready: if sock == socket: (newsock, address) = sock.accept() sock_list.append(newsock) data_dic[newsock] = '' rib_logger.info('New connection from '+str(address)) else: data_tmp = sock.recv(100000000) if len(data_tmp) == 0: rib_logger.info('One peer has Disconnected') sock.close() sock_list.remove(sock) else: data_dic[sock] += data_tmp next_data = '' while data_dic[sock][-1] != '\n': next_data = data_dic[sock][-1]+next_data data_dic[sock] = data_dic[sock][:-1] """ In case the peer wants to fast reroute""" for data_line in data_dic[sock].rstrip('\n').split('\n'): if data_line.startswith('FR'): data_line_tab = data_line.split('|') peer_ip = data_line_tab[1] vmac_partial = data_line_tab[2] bitmask_partial = data_line_tab[3] depth = int(data_line_tab[4]) ts = int(float(data_line_tab[5])) for f in vnh.insert_backup_rules(peer_ip, depth, vmac_partial, bitmask_partial): OFFlowsQueue.append((ts, f)) else: data_line_tab = data_line.split('|') peer_ip = data_line_tab[0] prefix = data_line_tab[1] ts = float(data_line_tab[2]) for f in OFFlowsQueue.refresh_iter(ts): with open('deleted_rules', 'a') as fd_del: fd_del.write(f+'\n') os.system('ovs-ofctl del-flows s1 '+f) """ In case it is an advertisement """ if len(data_line_tab) == 5: v_mac = data_line_tab[4] if len(data_line_tab[3]) > 0: try: as_path = map(lambda x:int(x), data_line_tab[3].split(' ')) except: print data_line_tab as_path = [] else: as_path = [] bgproute = BGPRoute(prefix, peer_ip, as_path, v_mac) prev_prim, new_prim, bgproute, prev_backup, new_backup = rib_global.announce(bgproute) vnh_ip, vnh_mac = vnh.get_VNH(prefix) print 'A|'+str(prefix)+'|'+str(vnh_ip)+'|('+str(vnh_mac)+')|'+str(' '.join(map(lambda x:str(x), new_prim.as_path))) """ In case it is a withdrawal """ else: prev_prim, new_prim, bgproute, prev_backup, new_backup = rib_global.withdraw(peer_ip, data_line_tab[1]) if new_prim is not None: vnh_ip, vnh_mac = vnh.get_VNH(prefix) print 'A|'+str(prefix)+'|'+str(vnh_ip)+'|('+str(vnh_mac)+')|'+str(' '.join(map(lambda x:str(x), new_prim.as_path))) else: if prev_prim is not None: print 'W|'+str(prefix) data_dic[sock] = next_data
import socket import threading port = 6464 host = 'localhost' socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) addr = socket.bind((host, port)) socket.listen(10) print("[*] ESPERANDO CONEXÃO ...") def conectarSocket(socket, adrr): print("Recebendo conexão de {}".format(adrr)) msgCliente = socket.recv(2543616).decode('utf-8') if msgCliente == '1': #abre o arquivo file = open('caminho', 'rb') #le 1024 bytes do arquivo l = file.read(1024) #enquanto tiver algo no arquivo ele vai enviando para o cliente a cada 1024 bytes while l: #enviar para o cliente parte a parte o arquivo socket.send(l) print('Enviado ', repr(l)) l = file.read(1024) #fecha o arquivo file.close() print("[*] ARQUIVO ENVIADO COM SUCESSO")
import socket import entity def process_data(entity, data): func_list = data.split(' ') for func_name in func_list: if len(func_name) > 0 : func = getattr(entity, func_name) if not func: print 'function %s not found!' % func_name continue func() if __name__ == '__main__': socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.bind(('127.0.0.1', 4000)) socket.listen(0) socket.setblocking(0) entity = entity.entity() clients = {} while True: conn = None addr = None try: conn, addr = socket.accept() except:pass if conn: print 'find new connection' clients[addr[0]+str(addr[1])] = conn for client_id, client in clients.iteritems():
import threading import socket socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #開啟 server 等待 client 進入 socket.bind( ( '',5550 ) ) socket.listen(5) print('Server listening ...') nickname_dir = {} people = [] def tellothers( exceptNum, words ): #發送 words 聊天室的其他人 for person in people: if person.fileno() != exceptNum: try: person.send(words.encode()) except: pass def room(person, person_id ): #將連線的 socket 設定 nickname , 並處理聊天室的公共事務( 廣播, server 轉發 ) nickname = person.recv(1024).decode() nickname_dir[person_id] = nickname people.append(person) print('connection',person_id,'has nickname : ',nickname) tellothers( person_id , '系統提示 '+nickname+' 進入聊天室') while 1: try: msg = person.recv(1024).decode() if msg: print(nickname, ":", msg) tellothers( person_id,nickname+ ":"+ msg )
import dns.message import dns.name import dns.query import dns.resolver from queue import LifoQueue tun = pytun.TunTapDevice(name='server_tun', flags=pytun.IFF_TUN | pytun.IFF_NO_PI) tun.addr = '10.10.10.2' tun.netmask = '255.255.255.0' tun.mtu = 160 tun.up() socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) socket.bind(('', 53)) query_queue = LifoQueue(65532) def decode_query(data: bytes): query_dns_pkt = dns.message.from_wire(data) name = str(query_dns_pkt.question[0].name) name = name[:-20] ip_data = ''.join(name.split('.')) write_to_tun_data = base64.b64decode(ip_data) return write_to_tun_data, query_dns_pkt def encode_response(send_to_socket_data: bytes, query_dns_pkt): response = dns.message.make_response(query_dns_pkt,
import sys import socket host = "" port = 13000 buf = 1024 socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) addr = (host, port) socket.bind(addr) while True: data, addr = socket.recvfrom(buf) data = data.decode() print("Recieved: " + str(type(data))) if data == "exit": socket.close() sys.exit()