class MuseAPI(object): def __init__(self, host): self.sock = MySocket() self.sock.client(host) self.lock = RLock() self.muse = MuseData() self._muse = MuseData() produce = Thread(target=self.handler) produce.daemon = True produce.start() def subscribe(self, k): self.sock.send('SUB ' + str(k)) def unsubscribe(self, k): self.sock.send('UNS ' + str(k)) def stop(self): self.sock.send('END') self.sock.sock.close() def update(self): with self.lock: self.muse.__dict__.update(enumerate(self._muse.__dict__)) def handler(self): while 42: try: data = self.sock.recv() except error: break with self.lock: self._muse.update(data) print('Close')
def __init__(self, host): self.sock = MySocket() self.sock.client(host) self.lock = RLock() self.muse = MuseData() self._muse = MuseData() produce = Thread(target=self.handler) produce.daemon = True produce.start()
def GetTemperature(sock): now = datetime.datetime.today() foldername = now.strftime('%y-%m-%d') foldername = LOGFOLDER + foldername + '\\CH6 T ' + foldername + '.log' foldername = os.path.normpath(foldername) try: myfile = open(foldername,'rb') except FileNotFoundError: #if file not present, try previous day's file now = now - datetime.timedelta(days=1) foldername = now.strftime('%y-%m-%d') foldername = LOGFOLDER + foldername + '\\CH6 T ' + foldername + '.log' foldername = os.path.normpath(foldername) myfile = open(foldername,'rb') ss = MySocket(sock) word = tail(myfile,2) word = word.split(',')[-1] ss.mysend(word.encode('utf_8')) now = datetime.datetime.today() T = float(word)*1000. print("Temperature sent at %s, T = %f mK" % (now.strftime('%y-%m-%d %H:%M:%S'),T)) ss.sock.close()
def GetTemperature(sock): now = datetime.datetime.today() foldername = now.strftime('%y-%m-%d') foldername = LOGFOLDER + foldername + '\\CH6 T ' + foldername + '.log' foldername = os.path.normpath(foldername) try: myfile = open(foldername, 'rb') except FileNotFoundError: #if file not present, try previous day's file now = now - datetime.timedelta(days=1) foldername = now.strftime('%y-%m-%d') foldername = LOGFOLDER + foldername + '\\CH6 T ' + foldername + '.log' foldername = os.path.normpath(foldername) myfile = open(foldername, 'rb') ss = MySocket(sock) word = tail(myfile, 2) word = word.split(',')[-1] ss.mysend(word.encode('utf_8')) now = datetime.datetime.today() T = float(word) * 1000. print("Temperature sent at %s, T = %f mK" % (now.strftime('%y-%m-%d %H:%M:%S'), T)) ss.sock.close()
class EmailMonitor: #As long as the shut down signal isn't sent then run program run = True #GMail service service = None last_email_id = -1 #Handle the email commands as they come. queue = deque([]) #Class to send messages to our socket socket_class = MySocket() def get_credentials(self): """ Gets credentials so that one may access a particular google account It is super important that you have full access to aforementioned account. """ credential_dir = os.environ['GOOGLE_CREDENTIALS_DIR'] credential_path = os.path.join(credential_dir, os.environ['GOOGLE_CREDENTIALS_FILE']) store = oauth2client.file.Storage(credential_path) credentials = store.get() if not credentials or credentials.invalid: print("Invalid credentials provided") socket_class.shutdown() sys.exit(1) return credentials def get_service(self): """ Sets up the service for future usage. """ credentials = self.get_credentials() http = credentials.authorize(httplib2.Http()) self.service = discovery.build('gmail', 'v1', http=http) def check_mail(self): """ The count serves to help us narrow down the time range, by counting iteration we can determine how much time has passed and therefore update our query accordingly """ cur_count = 0 error_count = 0 """ Search for messages from a given phone number """ from_query = "from:" + str(os.environ['PHONE_NUMBER_EMAIL']) """ Set our final query as concatination of previous queries """ query = str(from_query + " " + "in:inbox" + " " + "is:unread") while self.run: try: response = (self.service.users().messages().list( userId='me', q=query).execute()) messages = [] if 'messages' in response: messages.extend(response['messages']) """ First message will be different """ if messages[0]['id'] != self.last_email_id: for message in messages: if message['id'] == self.last_email_id: break else: message_text = ( self.service.users().messages().get( userId='me', id=message['id'], format='raw').execute()) message_info = { 'msg_id': message['id'], 'msg_txt': message_text['snippet'] } self.queue.append(message_info) self.last_email_id = messages[0]['id'] self.handle_queue() except errors.HttpError as error: print('An error occurred: %s' % error) error_count = error_count + 1 if error_count == 40: print("Terminating program due to excessive errors") self.send_text_message( "Terminating Program due to excessive errors") socket_class.shutdown() sys.exit(1) cur_count = cur_count + 1 time.sleep(2) def handle_queue(self): while self.queue: info_dic = self.queue.popleft() message_id = info_dic['msg_id'] command = str(info_dic['msg_txt']).lower().strip() if command == "complete shutdown": self.run = False self.mark_as_read(message_id) self.socket_class.send_message("end") self.send_text_message('Shutting Down after marking messages') #So here we would actually handle the commands elif self.run: self.socket_class.send_message(command) self.mark_as_read(message_id) #This exists in order to mark messages as read/ else: print("Marking message: " + command) self.mark_as_read(message_id) def send_text_message(self, message_text): message = MIMEText(message_text) message['to'] = os.environ['PHONE_NUMBER_EMAIL'] message['from'] = os.environ['GMAIL_PI_EMAIL'] raw = base64.urlsafe_b64encode(message.as_bytes()) raw = raw.decode() body = {'raw': raw} try: message = (self.service.users().messages().send( userId='me', body=body).execute()) except errors.HttpError as error: print('An error occurred: %s' % error) def run(self): self.get_credentials() self.get_service() #Check if the service was correctly set up if not self.service: print("Unable to correctly start service") socket_class.shutdown() sys.exit(1) self.check_mail() def send_unknown_error_alert(self): self.send_text_message("Unknown error occured") def send_final_shutdown_text(self): self.send_text_message("Program has concluded successfully") def mark_as_read(self, msg_id): payload = {'removeLabelIds': ['UNREAD'], 'addLabelIds': []} try: message = (self.service.users().messages().modify( userId='me', id=msg_id, body=payload).execute()) except errors.HttpError as error: print('An error occurred: %s' % error)
class Robot: power = 200 dt = 500 speed = 200 time = 10 socket = MySocket() colorS = ColorSensor() cs = ev3.ColorSensor(); tank = myMotor.MoveTank(OUTPUT_A, OUTPUT_B) tank.cs = ev3.ColorSensor() tank.ts = ev3.TouchSensor() assert cs.connected # measures light intensity cs.mode = 'COL-REFLECT' # measure light intensity # cs.mode = 'RGB-RAW' # measure light intensity lm = ev3.LargeMotor('outA'); assert lm.connected # left motor rm = ev3.LargeMotor('outB'); assert rm.connected # right motor def __init__(self, **kwargs): for keys, value in kwargs.items(): if (keys == "cmode"): self.cs.mode = targetMode(value) print("robo cmode: " + str(self.cs.mode)) def makesound(self): print("ready") while True: if self.tank.ts.is_pressed: break Sound.speak('Hello, my name is E V 3!').wait() Sound.speak('I play Tic Tac Toe').wait() Sound.speak('Oliver is preparing the GamingEnviroment').wait() Sound.speak('I hope he hurries').wait() Sound.speak('I am running out of text').wait() def makebeep(self): Sound.tone(264, 2000) def endGameSound(self): Sound.tone([(264,200,20),(268,200,20),(272,200,20)]).wait() def run_modes(self, ar, **kwargs): print("rmode: " + str(ar)) if(ar =="run"): self.run(**kwargs) elif(ar == "mea"): self.measure(**kwargs) elif(ar == "runmea"): self.run_measure(**kwargs) elif(ar=="fol"): self.follow_line(**kwargs) elif(ar=="way"): self.goWay(**kwargs) elif(ar=="speak"): self.makesound() elif (str(ar) != str("run")): print('a: ' + ar) print('a len: ' + str(len(ar))) print('a rep: ' + repr(ar)) print('b: ' + "run") print('b len: ' + str(len("run"))) print('b rep: ' + repr("run")) def run_measure(self,**kwarg): self.goWay(**kwarg) print(self.measure()) def measure(self,**kwarg): print("in measure with: "+ self.cs.mode) target_val = self.cs.value() self.cs.reflected_light_intensity print() print("target v:" + str(targetvalue(target_val))) print("red: " + str(self.cs.red)) print("green: " + str(self.cs.green)) print("blue:" + str(self.cs.blue)) print("raw: " + str(self.cs.raw)) self.cs.mode = 'COL-COLOR' print("in measure with: "+ self.cs.mode) print("COL COLOR") print("refl line foll u know u shit: " + str(self.cs.reflected_light_intensity)) print("target v:" + str(targetvalue(target_val))) print("red: " + str(self.cs.red)) print("green: " + str(self.cs.green)) print("blue:" + str(self.cs.blue)) print("raw: " + str(self.cs.raw)) messages = {'Aktion': 'Befehl', 'is': 2, 'found': False} if self.cs.red<86 and self.cs.blue>95 and self.cs.green>95: messages = {'Aktion': 'Befehl', 'is': 2, 'found': True} self.makebeep() return json.dumps(messages).encode('utf-8') def run(self,**kwarg): print("in run") print('kwarg: power '+str(kwarg.power)) self.lm.run_timed(speed_sp=kwarg.power, time_sp=dt, stop_action=stop_action) self.rm.run_timed(speed_sp=kwarg.power, time_sp=dt, stop_action=stop_action) def run_measuretry(self): ##tryout methode print("in run_measureTRY") self.lm.run_timed(speed_sp=power, time_sp=dt, stop_action=stop_action) self.rm.run_timed(speed_sp=power, time_sp=dt, stop_action=stop_action) self.measure(self) return 0 def change_C_Mode(self,mode): self.cs.mode=mode def turn(self,tank,**kwargs): tank.on_for_degrees(kwargs.get('lspeed'), kwargs.get('rspeed'), kwargs.get('degrees')) def turn_corner(self,**kwargs): print('turn') self.tank.on_for_degrees(kwargs.get('lspeed'), kwargs.get('rspeed'), kwargs.get('degrees')) while self.cs.reflected_light_intensity> kwargs.get('target_light_intensity')+2: print(self.cs.reflected_light_intensity) self.tank.on_for_degrees(kwargs.get('lspeed'), kwargs.get('rspeed'), 10) def follow_line(self, **kwargs): justFound=True #ensures robot doesnt stop at same edge where it starts while(True): res= self.tank.follow_line( folow_for=follow_for_ms,jf=justFound, **kwargs ) if res.get('return')=="off_line": print('offline') x = self.readjust(**res) justFound=False else: return res def readjust(self,**kwargs): right =False counter =0 mc=50 if kwargs.get('lms')< (kwargs.get('rms')): right=True while self.cs.reflected_light_intensity > kwargs.get('target_light_intensity')+2: print(counter) if(right): if counter<mc: self.tank.on_for_degrees(0, kwargs.get('rms') * -0.5, 10) else: self.tank.on_for_degrees(kwargs.get('lms') * -0.5, 0, 10) else: if counter<mc: self.tank.on_for_degrees(kwargs.get('lms') * -0.5, 0, 10) else: self.tank.on_for_degrees(0, kwargs.get('rms') * -0.5, 10) counter=counter+1 return True def goWay(self,**kwargs): orders=kwargs.get('way') strlen=len(orders) res={'return':"ecke"} for i in range (strlen) : if res.get('return')=="ecke": self.cs.mode='COL-REFLECT' if(orders[i]=='s'): res=self.follow_line(**kwargs) if(orders[i]=='r'): self.tank.on_for_seconds(kwargs.get('uspeed'),kwargs.get('uspeed'), kwargs.get('rot')) self.tank.on_for_degrees(kwargs.get('ulspeed'), kwargs.get('urspeed'), kwargs.get('degrees')) while self.cs.reflected_light_intensity > kwargs.get('target_light_intensity') + 2: self.tank.on_for_degrees(kwargs.get('rspeed'), kwargs.get('lspeed'), 10) self.follow_line(**kwargs) if (orders[i] == 'l'): self.tank.on_for_seconds(kwargs.get('uspeed'),kwargs.get('uspeed'), kwargs.get('rot')) self.tank.on_for_degrees(kwargs.get('urspeed'), kwargs.get('ulspeed'), kwargs.get('degrees')) while self.cs.reflected_light_intensity > kwargs.get('target_light_intensity') + 2: self.tank.on_for_degrees(kwargs.get('lspeed'), kwargs.get('rspeed'), 10) #self.tank.on_for_degrees(kwargs.get('rspeed'), kwargs.get('lspeed'), 10) self.follow_line(**kwargs) return True def turn_new(self,right=True,**kwargs): dirs= kwargs.get('rspeed') offdirs=kwargs.get('lspeed') self.tank.on_for_degrees(dirs,offdirs)
def main(): # Clear any cached data because both bluez and CoreBluetooth have issues with # caching data and it going stale. mysock = MySocket() if DEBUG: print("Connecting ips socket") # mysock.connect() # mysock.mysend() # i = 0 # while True: # mysock.mysend(str(i)) # i += 1 ble.clear_cached_data() # Get the first available BLE network adapter and make sure it's powered on. adapter = ble.get_default_adapter() adapter.power_on() if DEBUG: print('Using adapter: {0}'.format(adapter.name)) # Disconnect any currently connected UART devices. Good for cleaning up and # starting from a fresh state. if DEBUG: print('Disconnecting any connected UART devices...') UART.disconnect_devices() # Scan for UART devices. if DEBUG: print('Searching for UART device...') try: adapter.start_scan() # Search for the first UART device found (will time out after 60 seconds # but you can specify an optional timeout_sec parameter to change it). device = UART.find_device() if device is None: raise RuntimeError('Failed to find UART device!') finally: # Make sure scanning is stopped before exiting. adapter.stop_scan() print("Connecting to Device") device.connect() # Will time out after 60 seconds, specify timeout_sec parameter # to change the timeout. # Once connected do everything else in a try/finally to make sure the device # is disconnected when done. try: # Wait for service discovery to complete for the UART service. Will # time out after 60 seconds (specify timeout_sec parameter to override). if DEBUG: print('Discovering services...') UART.discover(device) # Once service discovery is complete create an instance of the service # and start interacting with it. uart = UART(device) # Write a string to the TX characteristic. while True: uart.write('T ') # print("Sent 'Hello world!' to the device.") # Now wait up to one minute to receive data from the device. # print('Waiting up to 60 seconds to receive data from the device...') received = uart.read(timeout_sec=60) if received is not None: # Received data, print it out. if (received[0] is 'T'): bin_array = map(bin,bytearray(received)) # print(bin_array) if DEBUG: print("Probe 1: " + str(((int(bin_array[1], 2) << 8) + int(bin_array[2], 2)) / 100.0) + "\tProbe 2: " + str(((int(bin_array[3], 2) << 8) + int(bin_array[4], 2)) / 100.0)) mysock.mysend(str((int(bin_array[1], 2) << 8) + int(bin_array[2], 2)) + "," + str((int(bin_array[3], 2) << 8) + int(bin_array[4], 2))) else: # Timeout waiting for data, None is returned. if DEBUG: print('Received no data!') # sleep(1) finally: # Make sure device is disconnected on exit. device.disconnect()
# ed: 입력값은 센서의 갯수만큼 input_size = 181 # ed: 출력값은 One hot vector로써 10개의 케이스로 나뉜다 output_size = 10 # 감가율 dis = 0.9 # 리플레이메모리 사이즈 REPLAY_MEMORY = 50000 # 최대 스텝개수 MAX_STEP = 5000 # ed: 데이터를 Socket으로부터 받아온다 dyrosRLdata = MySocket.MySocket() # 실제로 DQN을 학습하는 함수. targetDQN, mainDQN을 분리시켰다 def ddqn_replay_train(mainDQN, targetDQN, train_batch): x_stack = np.empty(0).reshape(0, mainDQN.input_size) y_stack = np.empty(0).reshape(0, mainDQN.output_size) for state, action, reward, next_state, done in train_batch: Q = mainDQN.predict(state) # 게임이 끝난 경우 if done: Q[0, action] = reward else: Q[0, action] = reward + dis * targetDQN.predict(next_state)[0, np.argmax(mainDQN.predict(next_state))]
#!/bin/python3 import socket from MySocket import MySocket from MaxSubArray import maxSubArraySum if __name__ == "__main__": IP = "chals3.umdctf.io" PORT = 6001 SUFFIX = '\n\n' addtuple = (IP, PORT) # create an INET, STREAMing socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client = MySocket(s) client.connect(IP, PORT) initialMessage = client.myreceive2Suffix(SUFFIX) print("{}\nMessage : {}".format(initialMessage, len(initialMessage))) response = "\n".encode() client.mysend(response) arr = client.myreceive2Suffix(SUFFIX) # Before passing the list along we have to clean the data, # becasue it is a string at this point print("{}\nArray : {}".format(arr, len(arr))) newarr = arr.lstrip("[").rstrip("]\n") listRes = list(newarr.split(", ")) listInts = list(map(int, listRes)) result = maxSubArraySum(listInts, len(listInts)) response = "{}, {}, {}".format(*result).encode()
MAX_FROM_SERVER = 53 serversocket = socket(AF_INET, SOCK_STREAM) hostname = gethostname() port = randint(3210, 4321) serversocket.bind((hostname, port)) serversocket.listen(5) print(hostname) client = Popen(['../client', hostname, str(port)], stdin=PIPE, stdout=PIPE) (clientsocket, _) = serversocket.accept() clientsocket = MySocket(clientsocket) from_client = [] from_server = [] def get_length_in_network_bytes(data): return len(data).to_bytes(2, byteorder='big') ''' def generate_random_asci_lowercase_line(): length = randint(MIN_BYTES, MAX_BYTES) chars = (choice(ascii_lowercase) for _ in range(length)) line = ''.join(chars) return line.encode(encoding='UTF-8')
def create_connection(): print('create connection') socket = MySocket() socket.connect(hostname, port) connections.append(socket) expected_messages.append([])
except: raise RuntimeError("Send message failed.") finally: self.dataBeingSent = False def receive(self): ''' A method that waits until it receives a message and returns that message, along with the IP address of the sender. :rtype: tuple ''' chunks = [] while True: chunk = self.sock.recv(2048) if chunk == b'': raise RuntimeError("socket connection broken") chunks.append(chunk) if chr(chunk[-1]) == '\x04': #ASCII EOT byte break #Returns (message, ip of sender) return (str(b''.join(chunks)[:-1])[2:-1].replace("\\n", "\n").rstrip(), self.sock.getpeername()[0]) if __name__ == "__main__": s = MySocket() s.sock.settimeout(0.25) print(s.try_connect('10.243.67.97', 1298))
import socket from MySocket import MySocket from os import listdir import pickle DNS_HOST = '' DNS_PORT = 49152 # o numero de porta pode ser entre 49152 e 65535 self_HOST = '' self_PORT = 50000 SIZE = 1024 # ver isso!! # send IP and domain to DNS with MySocket(socket.AF_INET, socket.SOCK_DGRAM) as s: s.dnsRegisterDomain("bois.com", DNS_HOST, DNS_PORT) data = s.recv(1024) print('Received', data.decode()) # wait for clients server_socket = MySocket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind((self_HOST, self_PORT)) server_socket.listen(1) conn, addr = server_socket.accept() print('\nConnected to:', addr) while True: files = listdir('../arquivos') client_choice = conn.recv(SIZE) # nao sabia qual parametro colocar client_choice = client_choice.decode()
from MySocket import MySocket from time import time, sleep data = ['This Is a A data', 'This Is a B data', 'This Is a C data'] s = MySocket() s.client(('localhost', 5000)) while 42: for d in data: s.send(d + str(time()))
import random from collections import deque from dqn4 import dqn4 as dqn #from dqn3 import dqn3 as dqn #from dqn2 import dqn2 as dqn #from dqn import dqn as dqn from MySocket import MySocket input_size = 4 output_size = 2 dis = 0.9 REPLAY_MEMORY = 50000 MAX_STEP = 500 cartpole = MySocket.MySocket() def ddqn_replay_train(mainDQN, targetDQN, train_batch): x_stack = np.empty(0).reshape(0, mainDQN.input_size) y_stack = np.empty(0).reshape(0, mainDQN.output_size) for state, action, reward, next_state, done in train_batch: Q = mainDQN.predict(state) if done: Q[0, action] = reward else: Q[0, action] = reward + dis * targetDQN.predict(next_state)[ 0, np.argmax(mainDQN.predict(next_state))]
# The second paramter is the order of the bits inside each byte. # According to the HX711 Datasheet, the second parameter is MSB so you shouldn't need to modify it. hx.set_reading_format("LSB", "MSB") # HOW TO CALCULATE THE REFFERENCE UNIT # To set the reference unit to 1. Put 1kg on your sensor or anything you have and know exactly how much it weights. # In this case, 92 is 1 gram because, with 1 as a reference unit I got numbers near 0 without any weight # and I got numbers around 184000 when I added 2kg. So, according to the rule of thirds: # If 2000 grams is 184000 then 1000 grams is 184000 / 2000 = 92. # hx.set_reference_unit(113) hx.set_reference_unit(-384) hx.reset() hx.tare() soc = MySocket() GPIO.setup(15, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) while True: try: # These three lines are usefull to debug wether to use MSB or LSB in the reading formats # for the first parameter of "hx.set_reading_format("LSB", "MSB")". # Comment the two lines "val = hx.get_weight(5)" and "print val" and uncomment the three lines to see what it prints. #np_arr8_string = hx.get_np_arr8_string() #binary_string = hx.get_binary_string() # print binary_string + " " + np_arr8_string # Prints the weight. Comment if you're debbuging the MSB and LSB issue. if GPIO.input(15) == GPIO.HIGH: hx.tare() print "Tare!"
import pickle DNS_HOST = '' DNS_PORT = 49152 server_HOST = '' server_PORT = 50000 SIZE = 1024 # ver isso!! state = "requestServerIP" MENU = '\n\nMENU\nDigite:\n1. Listar arquivos\n2. Solicitar arquivos\n3. Encerrar conexão\n' dFiles = None while True: if state == "requestServerIP": # send server's domain to DNS and get its IP with MySocket(socket.AF_INET, socket.SOCK_DGRAM) as s: s.dnsQuery("bois.com", DNS_HOST, DNS_PORT) data = s.recv(1024) if data.decode() == '-1': print('Error: Domain not found') state = "domainNotFound" else: server_HOST = data socketClient = MySocket(socket.AF_INET, socket.SOCK_STREAM) socketClient.connect((server_HOST, server_PORT)) state = "menu" # print('Received', data.decode()) elif state == "domainNotFound": m = str(input("Do you want to try to request the domain to the DNS server again? yes(y) or no(n)\n"))
# ed: 입력값은 센서의 갯수만큼 #input_size = 181+180 #181 + vectorLen + headingDiff input_size = 36 + 5 * 2 #181 + vectorLen + headingDiff # ed: 출력값은 One hot vector로써 #개의 케이스로 나뉜다 output_size = 3 * 3 # 감가율 dis = 0.9 # 리플레이메모리 사이즈 REPLAY_MEMORY = 50000 # 최대 스텝개수 MAX_STEP = 900000 # ed: 데이터를 Socket으로부터 받아온다 unityRLdata = MySocket.MySocket() checkpoint_name = "./test1.ckpt" #reward reward_cnt = 5 w0 = 1000 #충돌시 w1 = 100000 #goal도착 w2 = 10 #차와 goal간 방향이 잘 맞는 정도에 비례한 reward w2Exp = 1 #차수 w3 = 350 #차와 goal간 거리가 가까운 정도에 비례한 reward w3Exp = 3 #차수 w4 = 0.01 # 오래 살아 남으면 -> ----- ==> 빠르게 도달 할 수 있도록 # 실제로 DQN을 학습하는 함수. targetDQN, mainDQN을 분리시켰다
sendall() :TCP recvfrom() :UDP recvfrom_into() :UDP sendto() :UDP ''' HOST = 'localhost' # HOST = '::1' PORT = 9999 ADDR = (HOST, PORT) if __name__ == "__main__": # s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) # s.settimeout(5) # s.connect(ADDR) # print(s.recv(1024).decode('utf-8')) # for data in [b'Tony', b'Nick', b'Ulysses']: # s.send(data) # print(s.recv(1024).decode('utf-8')) # s.send(b'exit') # s.close() s = MySocket() s.connect(HOST, PORT) print(s.myreceive(32).decode('utf-8')) for data in [b'Tony', b'Nick', b'Ulysses']: print(len(data)) s.mysend(data) print(s.myreceive(32).decode('utf-8')) s.mysend(b'exit') s.close()
from socket import AF_INET, SOCK_DGRAM from MySocket import MySocket, MESSAGE_SIZE from Segment import Segment # # # # # CONSTANTS # # # # # SERVER_HOST = '' SERVER_PORT = 50004 # # # # # VARIABLES # # # # # state = "menu" # # # # # MAIN # # # # # s = MySocket(AF_INET, SOCK_DGRAM) # while True: # if state == "send_syn": # send connection request to server # connection_request = Segment(next_seq, syn='1') # next_seq += 1 # s.send_segment(connection_request, rcv_base, (SERVER_HOST, SERVER_PORT)) # # wait for ack and new socket port number # segment, client_addr = s.receive_segment() # if segment.syn == '1' and segment.ack_number != -1: # print('received SYN_ACK\n') # state = "established" # elif state == "established": # s.send_ack((SERVER_HOST, SERVER_PORT))
DNS_PORT = 49152 SELF_HOST = '' SELF_PORT = 50004 MENU = '\n\nMENU\nDigite:\n1. Listar arquivos\n2. Solicitar arquivos\n3. Encerrar conexão\n' # # # # # VARIABLES # # # # # client_sockets = {} state = "listen" # # # # # MAIN # # # # # # send IP and domain to DNS with MySocket(AF_INET, SOCK_DGRAM) as dns_socket: dns_socket.dnsRegisterDomain("bois.com", DNS_HOST, DNS_PORT) data = dns_socket.recv(MESSAGE_SIZE) print('Received', data.decode()) print() dns_socket.close() # connect to client s = MySocket(AF_INET, SOCK_DGRAM) s.bind((SELF_HOST, SELF_PORT)) # while True: # if state == "listen": # # wait for connection request # segment, client_addr = s.receive_segment()