def SetVolume(self): volume_label = int(self.volume * 10) self.volumeter = self.vol.UpdateText("volume: %1.0f" % (volume_label)) self.mustRender = True message = "VOLU %f " % self.volume Socket.socket_message(message)
def Stop(self): message = "STOP A" Socket.socket_message(message) self.SetNowPlaying("nothing") self.playing = False self.playback_position = 0 self.mustRender = True
def BurnCD(self, tracks, mode): # if there is no CD, do not start burning if mode == 'BURN_USB': mtype = 'Pendrive' else: mtype = 'CD-ROM' if not self.CheckMedia(mtype): return track_count = len( tracks.split(":") ) - 1 if mode == 'BURN_AUDIO': mode = 'A' self.decoding = True self.BurnMode = 'A' elif mode == 'BURN_DATA' : mode = 'D' self.burning = True self.BurnMode = 'D' elif mode == 'BURN_USB' : print "Called burner to USB" mode = 'U' self.burning = True self.BurnMode = 'U' self.ShowStarting(track_count) message = "BURN_"+mode+"_123|||" + tracks Socket.socket_message(message)
def sendMessage(self, message=None): if not self.__socket: return if not message: Socket.sendMessage(self.__socket) else: Socket.sendMessage(self.__socket, message, self.getChnlStr())
def BurnCD(self, tracks, mode): # if there is no CD, do not start burning if mode == 'BURN_USB': mtype = 'Pendrive' else: mtype = 'CD-ROM' if not self.CheckMedia(mtype): return track_count = len(tracks.split(":")) - 1 if mode == 'BURN_AUDIO': mode = 'A' self.decoding = True self.BurnMode = 'A' elif mode == 'BURN_DATA': mode = 'D' self.burning = True self.BurnMode = 'D' elif mode == 'BURN_USB': print "Called burner to USB" mode = 'U' self.burning = True self.BurnMode = 'U' self.ShowStarting(track_count) message = "BURN_" + mode + "_123|||" + tracks Socket.socket_message(message)
def __init__(self): """ initialise the server and instantiate w/ Socket.Socket().__init__() """ Socket.__init__(self) self._hostcache = {} self.clients = [] self.channels = []
def Play(self, filepath): '''Play the file''' self.playback_position = 0 #if self.browser.level == 'jamendo': file = filepath #else: file = urllib.url2pathname(filepath) file = urllib.url2pathname(filepath) #file = "\\ ".join( p for p in file.split(" ")) #logger.debug( "Play file : " + file ) message = "PLAY " + file pygame.mixer.quit() Socket.socket_message(message) self.playing = True
class TestSocket(unittest.TestCase): ''' Socket模块测试类 ''' def setUp(self): self.socket = Socket() self.socket.start() def tearDown(self): self.socket = None def test_init(self): self.assertTrue(self.socket.is_alive());
def __init__(self, model): # hyperparameters for loss terms, gamma is the discount coefficient self.step = 0 self.socket = Socket(HOST, receivePORT, sendPORT) self.params = {'gamma': 0.99, 'value': 0.5, 'entropy': 0.0001} self.model = model self.model.load_weights('./checkpoints/my_checkpoint') self.model.compile( optimizer=tf.keras.optimizers.RMSprop(lr=0.0007), # define separate losses for policy logits and value estimate loss=[self._logits_loss, self._value_loss])
def join_room(s): readbuffer = "" Loading = True while Loading: readbuffer = readbuffer + str(s.recv(1024)) print(readbuffer) temp = readbuffer.split('\\n') print(temp) readbuffer = temp.pop() for line in temp: Loading = loading_complete(line) Socket.send_message(s, "Successfully joined chat")
def communicate_video(self, cmd): """ video 서버 접속 및 데이터 통신 """ print(cmd) read_msg = "-ERR fail to connect video server\r\n" try: s = Socket.Socket() s.Connect(self.video_host, self.video_port) s.ReadMessage() # welcome msg s.SendMessage(cmd) read_msg = s.ReadMessage() s.SendMessage(b"QUIT 0\r\n") except Exception as err: print(str(err)) pass finally: try: s.close() except: pass rtn_val = "" print("ERRRRRRR!!! : ", read_msg) if read_msg[0] and len(read_msg) == 2: rtn_val = read_msg[1] # 연결 실패시 빈문자열 return str(rtn_val)
def __init__(self, Username, Password): self.user = User.User() self.user.Username = Username self.user.Password = Password self.Sock = Socket.SocketClient("204.75.167.165", 3724) self.Sock.Connect() self.StartLogin()
def openPort(self): """ """ if self.lock.acquire(): if (self.debug): print "Opening socket ip %s" % self.ip self.lw.write("Opening az/el socket ip %s " % self.ip) try: self.s = S.Socket(S.socket.AF_INET, S.socket.SOCK_STREAM) except S.socket.error, e: print "Error creating socket: %s" % e self.lock.release() sys.exit(1) try: self.s.connect((self.ip, self.port)) except socket.error, e: self.lw.write('Cannot open socket ip: %s at port %d' % (self.ip, self.port)) self.lw.write('Connection error: %s' % e) if self.debug: print 'Cannot open socket ip: %s at port %d' % (self.ip, self.port) if self.debut: print 'Connection error: %s' % e self.lock.release() sys.exit(1)
def bind(self): host = self._config['host'] port = self._config['port'] cert_file = self._config['cert_file'] key_file = self._config['key_file'] self.server_socket = Socket.ServerSocket(cert_file, key_file) self.server_socket.bind(host, port, 1) self._logger.log("Listening on {}:{}".format(host, port))
def connectSocket(self): if not self.isConnectionHealthy(): if (self.__gui.getOauthStr() and self.__gui.getNameStr() and self.__gui.getChnlStr()): self.__socket = Socket.openSocket( str(self.__gui.getOauthStr()), str(self.__gui.getNameStr()), str(self.__gui.getChnlStr())) self.isConnected(Initialize.joinRoom(self.__socket), True)
def __main__(): check_files_and_folders() socket = Socket.ServerSocket() connection = socket.Socket() sr = Server(connection, Cryptography.session_crypto(None), Registery.Registery(), Login.serverLogin(), Download.Download(), Upload.Upload(), List.List(), Read.Read(), Write.Write(), SessionKeyExchange.ServerSession(None), DACCommands.DACCommands(), Auditor.Auditor()) sr.Handler()
def host(self): self.hostButton.text = "WAITING" self.hostButton.callback = None sock = Socket.Server() print('i am server') self.sock = sock ctx['imHost'] = True ctx['sock'] = sock sock.connect() Scene.game.setScene(MainScene())
def join(self): self.joinButton.text = "WAITING" self.joinButton.callback = None sock = Socket.Client() print('i am client') self.sock = sock ctx['imHost'] = False ctx['sock'] = sock sock.connect() Scene.game.setScene(MainScene())
def __init__(self, title = "Welcome"): self.root = tkinter.Tk() self.root.title(title) self.root.configure(bg = "#004D40") self.root.maxsize(500, 400) self.root.minsize(500, 400) self.btnCommOn = False ### communication status with RaspBerryPi, TRUE or FALSE self.btnGpioOn = True ### SIGNAL LEVEL (On or Off) to GPIO self.sock = Socket.Socket(callback = self.getResult)
def openPort(self): """ Opens socket connection """ try: if self.debug: print "Opening socket ip %s"%self.ip self.s = S.Socket(S.socket.AF_INET, S.socket.SOCK_STREAM) self.s.connect((self.ip,self.port)) status = 0 except: self.lw.write('Cannot open socket ip: %s, port %d'%(self.ip,self.port)) status = 2 return status
def AgentConnect(self): self.sock = Socket.Socket() self.sock.Connect(self.ip, self.agent_port) msg = self.sock.Readline(False, 5) # WELCOME if (msg[0] != '+'): raise Exception, "Welcome Error !!!" self.sock.SendMessage("USER admin\r\n") msg = self.sock.Readline(False, 5) if (msg[0] != '+'): raise Exception, "Auth Error !!!" self.sock.SendMessage("PASS admin.\r\n") msg = self.sock.Readline(False, 5) if (msg[0] != '+'): raise Exception, "Password Error !!!" __LOG__.Trace("AgentConnect... ok")
def handle_new_conn(self, conn, addr): with conn: new_conn = Socket.Socket() serialised_data = new_conn.recv_data(conn) lock.acquire() try: data = message.Message().build_response(conn, serialised_data) if data['filename'] != 'errors.html': request_uri = serialised_data['request_uri'] if request_uri not in requests: requests[request_uri] = 1 else: requests[request_uri] = requests[request_uri] + 1 stdout = ''.join('%s | %s | %s | %d' % \ (request_uri, addr[0], addr[1] , requests[request_uri])) print(stdout) self.sock.send_data(conn, data) finally: lock.release() sys.exit(1)
def __init__(self): self.servernodes = [] noOfServers = 6 noOfSockets = 3 noOfNumanodes = 2 noOfCores = 8 nodeCounter = 0 coreCounter = 0 for m in range(noOfServers): snode = Servernode.Servernode(m) for n in range(noOfSockets): socket = Socket.Socket(n) for o in range(noOfNumanodes): node = Numanode.Numanode(nodeCounter) nodeCounter += 1 for p in range(noOfCores): core = Core.Core(coreCounter) coreCounter += 1 node.addCore(core) socket.addNumanode(node) snode.addSocket(socket) self.servernodes.append(snode) self.totalCores = coreCounter + 1
def run_server(self): WELCOME_MSG = b"+OK Welcome Video AI Server\r\n" while True: s = Socket.Socket() s.Bind(self.video_server_port) sock = s.Accept() print("Accept") sock.SendMessage(WELCOME_MSG) while True: try: line = sock.Readline() line = line.decode('utf-8') cmd, param = line.strip().split() print("CMD : ", cmd) print("param : ", param) ret_message = b"-ERR BAD\r\n" if cmd.upper() == "HEALTH_CHECK": ret_message = b'+OK 30\r\n' elif cmd.upper() == "SHOW_CURRENT": ret_message = b'+OK i dont know\r\n' ret_message = self.SHOW_CURRENT() elif cmd.upper() == "LAST_SHOW": ret_message = b'+OK i dont know\r\n' ret_message = self.LAST_SHOW(param) elif cmd == "QUIT": break print("CMD : **", cmd) sock.SendMessage(ret_message) except Exception as err: print(err) break try: sock.close() s.close() except: pass
def __init__(self): Thread.__init__(self) self.sock = Socket.get_socket() self.phrase = "" self.start()
def run_job(stock): s = Socket.Socket(stock)
from Socket import * import simplejson as json sckt = Socket() sckt._connect('localhost',13854) msg = {"appName":"testApp", "appKey":"b5b8b5374f7649ce322647506a80c30e2deb87cc"} print "authenticating..." sckt._send(msg) reply = sckt._receive() print ("authentication reply: %s") %reply msg = {"enableRawOutput": true, "format": "Json"} print "configuring..." sckt._send(msg)
import Socket server=Socket.Server()
class A2CAgent: def __init__(self, model): # hyperparameters for loss terms, gamma is the discount coefficient self.step = 0 self.socket = Socket(HOST, receivePORT, sendPORT) self.params = {'gamma': 0.99, 'value': 0.5, 'entropy': 0.0001} self.model = model self.model.load_weights('./checkpoints/my_checkpoint') self.model.compile( optimizer=tf.keras.optimizers.RMSprop(lr=0.0007), # define separate losses for policy logits and value estimate loss=[self._logits_loss, self._value_loss]) def train(self, batch_sz=240): # storage helpers for a single batch of data actions = np.empty((batch_sz, ), dtype=np.int32) rewards, values = np.empty((2, batch_sz)) observations = np.empty((batch_sz, ) + (718, )) points = [] while True: msg, client = self.socket.udp.recvfrom(8192) string_data = msg.decode('utf-8') if len(string_data) > 15: next_obs, reward = self.socket.process(string_data) rewards[self.step] = reward observations[self.step] = next_obs.copy() actions[self.step], values[ self.step] = self.model.action_value(next_obs[None, :]) if actions[self.step] == BUY: msg = "BUY" self.socket.udp.sendto(msg.encode('utf-8'), self.socket.dest) elif actions[self.step] == SELL: msg = "SELL" self.socket.udp.sendto(msg.encode('utf-8'), self.socket.dest) self.step += 1 if self.step >= batch_sz: self.step = 0 _, next_value = self.model.action_value(next_obs[None, :]) returns, advs = self._returns_advantages( rewards, values, next_value) acts_and_advs = np.concatenate( [actions[:, None], advs[:, None]], axis=-1) print("Training") losses = self.model.train_on_batch( observations, [acts_and_advs, returns]) print("Training finished") logging.info("Losses: %s ", losses) self.model.save_weights('./checkpoints/my_checkpoint') def _returns_advantages(self, rewards, values, next_value): # next_value is the bootstrap value estimate of a future state (the critic) returns = np.append(np.zeros_like(rewards), next_value, axis=-1) # returns are calculated as discounted sum of future rewards for t in reversed(range(rewards.shape[0])): returns[t] = rewards[t] + self.params['gamma'] * returns[t + 1] returns = returns[:-1] # advantages are returns - baseline, value estimates in our case advantages = returns - values return returns, advantages def _value_loss(self, returns, value): # value loss is typically MSE between value estimates and returns return self.params['value'] * tf.keras.losses.mean_squared_error( returns, value) def _logits_loss(self, acts_and_advs, logits): # a trick to input actions and advantages through same API actions, advantages = tf.split(acts_and_advs, 2, axis=-1) # sparse categorical CE loss obj that supports sample_weight arg on call() # from_logits argument ensures transformation into normalized probabilities weighted_sparse_ce = tf.keras.losses.SparseCategoricalCrossentropy( from_logits=True) # policy loss is defined by policy gradients, weighted by advantages # note: we only calculate the loss on the actions we've actually taken actions = tf.cast(actions, tf.int32) policy_loss = weighted_sparse_ce(actions, logits, sample_weight=advantages) # entropy loss can be calculated via CE over itself entropy_loss = tf.keras.losses.categorical_crossentropy( logits, logits, from_logits=True) # here signs are flipped because optimizer minimizes return policy_loss - self.params['entropy'] * entropy_loss
def server_3(): # Sockets from which we expect to read inputs = [server] # Sockets to which we expect to write outputs = [] while inputs: # Wait for at least one of the sockets to be ready for processing # print("\nwaiting for the next event") readable, writable, exceptional = select.select( inputs, outputs, inputs) # Handle inputs for s in readable: if s is server: # A "readable" server socket is ready to accept a connection connection, client_address = s.accept() # print("new connection from", client_address) connection.setblocking(0) Socket.set_socket_keep_alive(connection, keep_alive_time=5, keep_alive_interval=10, max_probes=10) inputs.append(connection) # Give the connection a queue for data we want to send message_queues[connection] = Queue() else: data = s.recv(1024) if data: command, *params = data.split(b' ') # A readable client socket has data print('received "%s" from %s' % (data, s.getpeername())) if command == b'ping': message_queues[s].put(b'pong') elif command == b'pong': message_queues[s].put(b'ping') elif command == b'kill': message_queues[s].put(b'GoodBy!') for s in inputs: s.close() inputs = [] elif command == b'echo': message_queues[s].put(b' '.join(params)) elif command == b'time': message_queues[s].put( str(datetime.datetime.now().time()).encode( encoding='utf-8')) elif command == b'download': download_file(s, params[0]) else: message_queues[s].put( b'unknown command, please try again') # Add output channel for response if s not in outputs: outputs.append(s) inputs.remove(s) else: if s in outputs: outputs.remove(s) inputs.remove(s) s.close() # Remove message queue del message_queues[s] # Handle outputs for s in writable: try: if s in in_download: download_file(s) next_msg = message_queues[s].get_nowait() except Empty: # No messages waiting so stop checking for writability. print("output queue for", s.getpeername(), "is empty") if s in outputs: outputs.remove(s) else: if next_msg == 'close M**********R': s.close() outputs.remove(s) else: # print('sending "%s" to' % (next_msg)) s.send(next_msg) # Handle "exceptional conditions" for s in exceptional: print("handling exceptional condition for", s.getpeername()) # Stop listening for input on the connection inputs.remove(s) if s in outputs: outputs.remove(s) s.close() # Remove message queue del message_queues[s]
def __init__(self, window): Thread.__init__(self) self.root_window = window self.sock = Socket.get_socket() self.start()
import Socket import os Socket.Client().run_client()
import Socket client=Socket.Client()
def setUp(self): self.socket = Socket() self.socket.start()
#!/usr/bin/env python import Socket if __name__ == "__main__": server = 'localhost' port = 50007 sock = Socket.create_client(server,port) data = "Windows" Socket.send_data(sock,data) while True: result = Socket.receive_data(sock) print result Socket.close(sock)