def start(self): global socket socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.bind((self.host, self.port)) socket.listen(5) print("Load balancer is now running at {}:{}".format( self.host, self.port)) print() while True: try: # Accept a request from the client connection, address = socket.accept() if self.verbose: print_lock.acquire() print("Received a connection from:", address) print_lock.release() start_new_thread(self.threaded_connection, (connection, address)) except: socket.close() return
def init(): socket.bind(('', 1550)) socket.listen(5) print('Waiting for connexion...') client, address = socket.accept() print("{} connected".format(address)) print('Generate key...') key = Fernet.generate_key() print('Done') print('Saving key with base64...') with open('key_for_' + str(address) + '.txt', 'w') as f: f.write(base64.b64encode(key).decode('utf-8')) f.close() print('Done') print('Sending key...') client.send(base64.b64encode(key)) print('Done')
def listen(socket, queue): while True: socket.listen(5) connection, address = serverSocket.accept() queue.put(connection)
def bind_and_listen_on_posix_socket(socket_name, accept_callback): """ :param accept_callback: Called with `PosixSocketConnection` when a new connection is established. """ assert socket_name is None or isinstance(socket_name, six.text_type) assert callable(accept_callback) # Py2 uses 0027 and Py3 uses 0o027, but both know # how to create the right value from the string '0027'. old_umask = os.umask(int('0027', 8)) # Bind socket. socket_name, socket = _bind_posix_socket(socket_name) _ = os.umask(old_umask) # Listen on socket. socket.listen(0) def _accept_cb(): connection, client_address = socket.accept() # Note: We don't have to put this socket in non blocking mode. # This can cause crashes when sending big packets on OS X. posix_connection = PosixSocketConnection(connection) accept_callback(posix_connection) get_event_loop().add_reader(socket.fileno(), _accept_cb) logger.info('Listening on %r.' % socket_name) return socket_name
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 __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 remoteListener(socket): socket.bind( ("", 8085) ) #80815 is the port this socket will be listening for, this number has to match the remote port assigned in the app. socket.listen(1) #set how many connections to accept remoteConnection, address = socket.accept() while True: try: buf = remoteConnection.recv(1024) buf = buf.decode("utf-8") print(buf) if len(buf) > 0: if buf == commands[0]: moveForward() elif buf == commands[1]: moveBackward() elif buf == commands[2]: turnLeft() elif buf == commands[3]: turnRight() elif buf == commands[4]: toggleLights() elif buf == commands[8]: turnOffMotors() else: remoteConnection, address = socket.accept() except Exception as e: print(e) break
def remoteListener(socket): socket.bind( ("", 8085) ) #80815 is the port this socket will be listening for, this number has to match the remote port assigned in the app. socket.listen(1) #set how many connections to accept remoteConnection, address = socket.accept() while True: try: buf = remoteConnection.recv(1024) buf = buf.decode("utf-8") if len(buf) > 0: print(buf) #use 'buf' to to call functions or perform actions based on it's value, EXAMPLE: if buf == "forward": moveForward() elif buf == 'disconnect': print( "app is attempting to disconnect" ) #you could use this for your own terminate function here or just ignore else: remoteConnection, address = socket.accept() except Exception as e: #print(e) break
def imageStreamer(socket): cam = cv2.VideoCapture(0) socket.bind(("",8081)) # 8081 is the port this socket will be listening for, this number has to match the video port assigned in the app. socket.listen(1) cam.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, 1280)#modify to set camera resolution width cam.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, 720)#modify to set camera resolution height imageQuality = 50 #1-100 higher = better quality but more data # set flip image to True if you want the image to be flipped flipImage = False while True: try: client,address = socket.accept() ret,camImage = cam.read() if flipImage: camImage = cv2.flip(camImage,1) # reduce size of image for potentially faster streaming. Keep the 'fx' and 'fy' values the same or the image will become skewed. camImage = cv2.resize(camImage, (0,0), fx=0.5, fy=0.5) byteString = bytes(cv2.imencode('.jpg', camImage,[int(cv2.IMWRITE_JPEG_QUALITY), imageQuality])[1].tostring()) fileSize = len(byteString) totalSent = 0 byteString = structureByteHeader(str(fileSize).encode(),8)+byteString totalSent = 0 while totalSent < fileSize: totalSent += client.send(byteString[totalSent:]) except Exception as e: print(e) break
def create_connection(): #| try: #| global host #| global LHOST #| global LPORT #| global socket #| #| LHOST = input(SUCCESS + 'Set LHOST: ') #| LPORT = input(SUCCESS + 'Set LPORT: ') #| host = LHOST + ':' + str(LPORT) #| socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #| except Exception as sok_Err: #| print(ERROR + 'Socket creation error: ' + str(sok_Err)) #| print(ERROR + 'Check create_connection(), Quitting....') #| #create_thread() #| #| #def socket_bind(): #| try: #| print('\n') #| print(WAITING + 'Binding socket to Host ' + str(host)) #| socket.bind((LHOST, int(LPORT))) #| socket.listen(6) #| time.sleep(0.5) #| print(SUCCESS + 'Binding successful.') #| time.sleep(0.7) #| print(WAITING + 'Waiting for connections.....') #| accept_multi_connections() #| except Exception as sok_Err: #| print(ERROR + 'Socket binding error: ' + str(sok_Err) + '\n\n\t' + 'Retrying...') #|
def manual(): print('Starting manual mode...') turret_active = True # bind pwm in @arduino via nanpy (knob) to turret rot # bind 2/3-pos switch to tilt via nanpy # bind 2-pos switch to capture start/stop + delay writz via console try: # delay is stored in capture.cfg - could add user prompt for auto file write later duration = input('How long do you want capture to run (seconds)? ') name = input('What name do you want for your KLG file? ') destination = '/home/logger/logs/' + name + '.klg' print('Destination is: ' + destination) capture.prepare_and_run_capture(duration, destination) # mandatory turret = Turret() print('Starting client...') vehicle.start_client('192.168.0.102', 'pi', 'aqw743zsx') # start client print('Listening to client for ' + duration + ' seconds...') socket.listen(5) # listening for radio_knob_level update client, address = socket.accept() print("{} connected".format( address )) print("Press Ctrl+C to stop...") last_pwm_input = int(787/2) last_tilt_input = int(787/2) max_time = time.time() + int(duration) while(turret_active): response = client.recv(255) try: response_int = int(response) print('Int response: ' + str(response_int)) response_str = str(response_int) except: print('Bad data received from client...') if response != "": radio_knob_level = int(response_str[0] + response_str[1] + response_str[2] + response_str[3]) print('Pan: ' + str(radio_knob_level)) radio_tilt_level = int(response_str[4] + response_str[5] + response_str[6] + response_str[7]) print('Tilt: ' + str(radio_tilt_level)) # execute command after data fetch turret.write_pwm_pan(radio_knob_level, last_pwm_input) turret.write_pwm_tilt(radio_tilt_level, last_tilt_input) last_pwm_input = radio_knob_level last_tilt_input = radio_tilt_level if radio.get_2_pos_level() >= 100: turret_active = False elif time.time() > max_time: turret_active = False print("Closing server connection...") client.close() socket.close() manual_stop() except KeyboardInterrupt: sys.exit("The program will now stop.")
def main(): socket.bind(('', port)) print("Socket is created with port %s" % port) socket.listen(5) print("Listening") while True: connection, address = socket.accept() print("Got Connected with ", address) start_time = time.time() child_pid = os.fork() if child_pid == 0: print("Process", address) socket.close() while True: data = connection.recv(2049).decode() command, key, value = parse_message(data) if command in ('GET', 'GETLIST', 'INCREMENT', 'DELETE'): response = COMMAND_HANDLERS[command](key) elif command in ( 'PUT', 'PUTLIST', 'APPEND', ): response = COMMAND_HANDLERS[command](key, value) else: response = (False, 'Unknown command type [{}]'.format(command)) update_stats(command, response[0]) connection.sendall('{};{}'.format(response[0], response[1])) if not data: break os._exit(0) print("child pid is %d" % child_pid) c.close()
def socket_bind(socket: socket.socket, addr) -> bool: try: socket.bind(addr) socket.listen(5) return True except: return False
def acceptNewClient(socket): #accept client connections print("listening & waiting for client to connect \n") socket.listen() connection, appSocket = socket.accept() print("client connected \n") return connection
def server_thread(self, socket): socket.listen(10) while True: conn, addr = socket.accept() clientt = threading.Thread(target=self.client_thread, args=(conn, )) clientt.start()
def listenAndCreateNewSession(): max_connections = 50 while True: socket.listen(max_connections) clientSocket, addr = socket.accept() example = Oracle(key, flag, IV, message, clientSocket, addr) return
def run(self): while True: socket.listen(5) client, address = socket.accept() response = client.recv(1000000) serponse = parse(response) if serponse != "": print serponse
def __prepare_read(self, input_id): input_format, socket, conn, file_like = self.inputs[input_id] if not conn: socket.listen(1) c = socket.accept() new_conn, addr = c conn = new_conn self.inputs[input_id] = (input_format, socket, conn, conn.makefile())
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 startVideoGeneratorServer(): server_address = (settings.server_location, int(settings.server_port_vid_gen)) print('Starting video generator server on %s port %s' % server_address) socket.bind(server_address) socket.listen(5) thread = Thread(target=waitConnect) thread.start() servertick = Thread(target=serverTick) servertick.start()
def recv_from_gh_client(socket): socket.listen() conn, _ = socket.accept() with conn: return_byt = conn.recv(65536) return_str = return_byt.decode() return_lst = [float(value) for value in return_str.split()] return return_lst
def listenToClients(numUsers, counterReady, socket, SendingInformation, threadNumber): ''' :param numUsers: The number of users :param counterReady: The counter to check if all the users are ready to listen :param socket: the dictionary of sockets to send to :param SendingInformation: the data to be sent :param threadNumber: the thread number which has teh lock over this function :return: None ''' print "\nlistening to client numUsers =", numUsers.value, " user id =", threadNumber socket.listen(10) conn, addr = socket.accept() counterReady.value += 1 data = "" payloadLength = struct.calcsize("i") flag = False print(counterReady.value) while True: print(counterReady.value) print("Thread " + str(threadNumber) + " Receiving") while len(data) < payloadLength: data += str(conn.recv(4096)) data = str(data) msgSize = data[:payloadLength] data = data[payloadLength:] # msgSize = str.encode(msgSize) msg_size = struct.unpack("i", msgSize)[0] while len(data) < msg_size: data += str(conn.recv(4096)) frame_data = data[:msg_size] data = data[msg_size:] if counterReady.value == numUsers.value: if flag == False: print("counter is " + str(numUsers.value)) for key in SendingInformation.keys(): t = SendingInformation[key] print("t[0]: ", str(t[0])) print("t[1]: ", str(t[1])) print("t[2]: ", str(t[2])) t[0].connect((t[2], int(t[1]))) flag = True for key in SendingInformation.keys(): print("sending frames to " + str(SendingInformation[key])) SendingInformation[key][0].sendall( struct.pack("i", len(frame_data)) + frame_data)
def listen_safely(socket): logger.debug('Trying to listen the socket on host [{}:{}]'.format(HOST, PORT)) try: socket.listen(LISTEN_QUEUE_SIZE) except: logger.error('Unable to listen the socket on host [{}:{}]: {}'.format(HOST, PORT, sys.exc_info()[0])) close_safely(socket) raise logger.debug('Successfully listening the socket on host [{}:{}]'.format(HOST, PORT))
def listenIn(socket): """Creates a listening channel""" try: socket.listen(5) except: socket.close() print("An error has occurred while listening, Server will now close") quitProgram() print("Socket is now listening")
def startServer(self): #startServer global socket socket = socket(AF_INET, SOCK_STREAM) host = gethostname() socket.bind((host, portNumber)) socket.listen(1) global connection connection, addr = socket.accept() isInitialized = True
def startVideoGeneratorServer(): server_address = ('localhost', 11000) print('Starting video generator server on %s port %s' % server_address) socket.bind(server_address) socket.listen(5) thread = Thread(target=waitConnect) thread.start() servertick = Thread(target=serverTick) servertick.start()
def build_simple_server(server_address: Address) -> None: # function anotations import socket socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.bind(server_address) while True: socket.listen() client, address = socket.accept() data = client.recv() print(str(data, encoding='utf-8'))
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 listen(socket, queue): while True: socket.listen(5) connection, address = serverSocket.accept() # users_in_db = users_db.query("SELECT * FROM user_table WHERE 'id' = ?", str(address[0])) # if len(users_in_db) == 0: # game_db.inser_data("games",[str(address[0])]) queue.put(connection)
def run(self): """Program go through infinite loop and wait for input on any one of the of the two sockets (csout and crout) and set their default receiver to the port numbers used by sender and receiver for the sockets sin and rin. """ rlist = [self.socketcsin, self.socketcrin] sendConn = None recvConn = None while True: read, write, error = select.select(rlist, [], []) for socket in read: if socket == self.socketcsin: socket.listen(10) sendConn, addr = socket.accept() print("Packet received from sender") rlist.append(sendConn) packet = sendConn.recv(self.maxBuffSize) self.socketcrout.connect((self.localHost, self.rin)) print("Packet processed and ready to send") self.socketcrout.send(packet) print("Packet Sent to receiver") elif socket == self.socketcrin: socket.listen(10) recvConn, addr = socket.accept() print("Packet received from receiver") rlist.append(recvConn) packet = recvConn.recv(self.maxBuffSize) self.socketcsout.connect((self.localHost, self.sin)) print("Packet processed and ready to send") self.socketcsout.send(packet) print("Packet Sent to sender") elif socket == sendConn: packet = sendConn.recv(self.maxBuffSize) if packet == "": #No incoming packets return decodedPacket = Packet.decode(packet) print("Packet recieved from sender sc") packet = self.introduceBitError(packet) if packet is not None: self.socketcrout.send(packet) print("Packet Sent to receiver sc") elif socket == recvConn: packet = recvConn.recv(self.maxBuffSize) if packet == "": #No incoming packets return decodedPacket = Packet.decode(packet) print("Packet received from receiver rc") packet = self.introduceBitError(packet) if packet is not None: self.socketcsout.send(packet) print("Packet Sent to sender rc")
def hosting(socket, port=30000): """ apre una porta sull'uscita n "port" :param socket: il socket :param port: numero porta :return: """ socket.bind(('', port)) socket.listen(1) conn, addr = accepting(socket) return conn, addr
def servidor(port): SERVER_PORT = port # inicializar a lista / conjunto de todos os soquetes do cliente conectado client_sockets = set() # create a TCP socket socket = socket.socket() # tornar a porta uma porta reutilizável socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # ligar o socket ao endereço que especificamos socket.bind((SERVER_HOST, SERVER_PORT)) # escute as próximas conexões socket.listen(5) print(f"[*] Listening as {SERVER_HOST}:{SERVER_PORT}") def listen_for_client(cs): """ Esta função continua ouvindo uma mensagem do socket `cs` Sempre que uma mensagem for recebida, transmita-a para todos os outros clientes conectados """ while True: try: # continue ouvindo por uma mensagem do socket `cs` msg = cs.recv(1024).decode() except Exception as e: # cliente não está mais conectado # remova-o do conjunto print(f"[!] Error: {e}") client_sockets.remove(cs) else: # se recebemos uma mensagem, substitua o <SEP> msg = msg.replace(SEPARAR_TOKEN, ": ") # iterar sobre todos os sockets conectados for client_socket in client_sockets: # e envia a msg client_socket.send(msg.encode()) while True: # continua atentos a novas conexões o tempo todo client_socket, client_address = socket.accept() print(f"[+] {client_address} connected.") # adicione o novo cliente conectado aos sockets conectados client_sockets.add(client_socket) # inicie um novo tópico que ouça as mensagens de cada cliente thread = Thread(target=listen_for_client, args=(client_socket,)) # faz o thread daemon para que ele termine sempre que o thread principal terminar thread.daemon = True # inicia a thread thread.start() # fecha client sockets for cs in client_sockets: cs.close() # fecha servidor socket socket.close()
def connect(socket): socket.listen(1) while True: print "Listening to connection.." connection, client = socket.accept() try: connection.sendall(data) print data d= connection.recv(1024) print d finally: return d
def listen(self, socket): try: socket.listen(1) self._print("Listening for 1 client...") conn, address = socket.accept() self._print("Accepted client connection...") except Exception, e: print e print "Error listening for clients" exit(1)
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 func_name1(): import socket s = socket.socket(socket.AF_INET,SOCK_STREAM) #socket.AF_INET-->基于IP的; SOCK_STREAM-->tcp/ip s.bind(('127.0.0.1',8125)) #输入的是一个元组(ip,端口)-->绑定ip和端口 socket.listen(8) #n代表允许多少个同时请求,超过的需要等待队列 while True: connection,address = s.accept() #没有请求的时候会停在这里 buf = connection.recv(1024) connection.send(buf) s.close()
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 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)
import socket import sys # Create a TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Bind the socket to the port server_address = ('localhost', 10000) print >>sys.stderr, 'starting up on %s port %s' % server_address sock.bind(server_address) socket.listen()
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(): data = ''
import struct import socket import json import time from utils import recv_one_message, send_one_message port = 5555 socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.bind(('localhost', port)) socket.listen(1) # become a server socket, maximum 5 connections # block for connection print("Waiting for connection from client...") client, addr = socket.accept() print("Got connection to {}".format(client)) # Got a hello world recieved = recv_one_message(client) if recieved == "Hello qgis": print("Got hello message {}".format(recieved)) print("Sending some commands now..") data = dict(command="new-layer", name="my layer", type="Point?crs=epsg:4326" ) send_one_message(client, data) time.sleep(1.2)
#!/usr/bin/python #Python version is 2.7.9 #Author: Martin Schmidt aka qw2100m import socket import time import select HOST = "" PORT = 2269 socket.listen(max_players) class Server(): def __init__(self, host, port): self.HOST = host self.PORT = port self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.bind((HOST, PORT)) def wait_for_connections(self): """Just wait for everybody to connect.""" self.max_players = input("Max number of players:") # Sockets from which we expect to read inputs = [ server ]
lproto = sys.argv[1] lport = int(sys.argv[2]) outfile = sys.argv[3] print "Firing up " + lproto + " listener on ", lport print "Writing to file", outfile print "-------------------------------------" if lproto == "tcp": proto = socket.SOCK_STREAM elif lproto == "udp": proto = socket.SOCK_DGRAM else: sys.exit("Wrong protocol.") socket = socket.socket(socket.AF_INET, proto) socket.bind(("", lport)) socket.listen(5) while 1: connection, addr = socket.accept() print "New connection from: ", addr data = connection.recv(1024) connection.close() print "Data received: ", data outputfile = open(outfile, "a") outputfile.write(data) socket.close() outputfile.close()
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
print "camera rotation: %s" % (camera.rotation,) print "camera on" print "cameraresolution: %s" % (camera.resolution,) print "framerate: %s" % (camera.framerate,) print "brightness: %s" % (camera.brightness,) except Exception as instance: print "Unable to enable the camera: %s" % (instance,) exit("1") # setup a socket to listen on port 80 try: socket = socket.socket() host = "" port = 82 socket.bind((host, port)) socket.listen(82) print "socket set up" except Exception as instance: print "Unable to setup a listening socket: %s" % (instance,) exit("1") # this will run forever until the the socket closes / client disconnects / error in socket occurs while True: try: connection, addr = socket.accept() worker = Thread(target=listenForBytes, args=(connection,multiWrite)) worker.setDaemon(True) worker.start() print "Got connection from %s %s" % (connection, addr)
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) ) print(question1) conn.send(createMsg(ans)) break
import socket HOST = '' PORT = 6030 socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.bind((HOST, PORT)) socket.listen(2) conexion, address = socket.accept() print ("Cliente: ", address) while 1: data = conexion.recv(1024) if not data: break else: print (data) #coneccion.send(data) dataa = input("Escrbe una respuesta: ") conexion.send(dataa.encode("utf-8")) conexion.close()
def listenAccept(self, socket): socket.listen(1) sck, address = socket.accept() self.socketHost = sck
modeLabel.setLabel('Navigation') #print modeLabel.getId() win.addControl(modeLabel) #blocking simple server-blocking in order to clean up if connection expires. host = socket.gethostname() port = 50000 backlog = 5 size = 1024 socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) socket.bind((host,port)) socket.listen(backlog) #socket.settimeout(60) socketFlag = True try: connection, address = socket.accept() except timeout: print "waiting connection timed out" socketFlag = False while socketFlag: try: data = connection.recv(1024) #Do things #possibly implement this as json handler at some point print data
def createServer(socket): print 'Starting server on %s:%s' % server_addr socket.bind(server_addr) socket.listen(5)