[LABI] tema03 src added

This commit is contained in:
TiagoRG 2023-03-24 18:46:20 +00:00
parent 65487cae03
commit 3e7e0aa5b5
6 changed files with 143 additions and 0 deletions

View File

@ -0,0 +1,19 @@
import socket
def main(args=None):
tcp_s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp_s.connect(('localhost', 1234))
while True:
str_data = input("$ ")
if not str_data or str_data == "stop":
break
tcp_s.send(str_data.encode("utf-8"))
b_data = tcp_s.recv(4096)
print("-> " + b_data.decode("utf-8"))
if __name__ == '__main__':
main()

View File

@ -0,0 +1,22 @@
import socket
def main(args=None):
tcp_s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp_s.bind(('', 1234))
tcp_s.listen(1)
client_s, client_addr = tcp_s.accept()
while True:
b_data = client_s.recv(4096)
if not b_data or b_data == "stop":
break
client_s.send(b_data.upper())
client_s.close()
tcp_s.close()
if __name__ == '__main__':
main()

View File

@ -0,0 +1,25 @@
import select
import socket
import sys
def main():
udp_s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp_s.bind(("127.0.0.1", 0))
server_addr = ("127.0.0.1", 1234)
while True:
rsocks = select.select([udp_s, sys.stdin], [], [])[0]
for sock in rsocks:
if sock == udp_s:
b_data, addr = udp_s.recvfrom(4096)
sys.stdout.write(f"-> {b_data.decode('utf-8')}")
elif sock == sys.stdin:
print('<- ', end='')
msg = sys.stdin.readline()
udp_s.sendto(msg.encode("utf-8"), server_addr)
if __name__ == '__main__':
main()

View File

@ -0,0 +1,31 @@
import socket
def main():
udp_c = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp_c.bind(("127.0.0.1", 1234))
addr_list = []
while True:
b_data, addr = udp_c.recvfrom(4096)
print(f"Received from {addr}: {b_data.decode('utf-8')}")
if addr not in addr_list:
addr_list.append(addr)
if b_data.decode("utf-8") == "stop":
print("Stopping server...")
break
for laddr in addr_list:
if laddr == addr:
continue
print(f"Sending to {laddr}: {b_data}")
udp_c.sendto(b_data, laddr)
udp_c.close()
if __name__ == "__main__":
main()

View File

@ -0,0 +1,23 @@
import socket
def main():
udp_s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp_s.bind(("127.0.0.1", 0))
server_addr = ("127.0.0.1", 1234)
while True:
msg = input(f"$ ")
udp_s.sendto(msg.encode("utf-8"), server_addr)
if msg == "stop":
break
b_data, addr = udp_s.recvfrom(4096)
print(f"-> {b_data.decode('utf-8')}")
udp_s.close()
if __name__ == '__main__':
main()

View File

@ -0,0 +1,23 @@
import socket
def main():
udp_c = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp_c.bind(("127.0.0.1", 1234))
while True:
b_data, addr = udp_c.recvfrom(4096)
print(f"Received from {addr}: {b_data.decode('utf-8')}")
if b_data.decode("utf-8") == "stop":
print("Stopping server...")
break
print(f"Sending to {addr}: {b_data.upper()}")
udp_c.sendto(b_data.upper(), addr)
udp_c.close()
if __name__ == "__main__":
main()