Commit e95b31c8 authored by Alan Marchiori's avatar Alan Marchiori
Browse files

added tcp

parent b0cc805b
"""
Simple udp client to illustrate local port assignment for udp sockets
Run any server or us nc as:
$ nc -lku localhost 8888
(l)isten
(k)eep listening (else stop after one client connection)
(u)dp
Alan Marchiori
"""
import socket
TCP_IP = "127.0.0.1"
TCP_PORT = 3333
print ("TCP target IP:", TCP_IP)
print ("TCP target port:", TCP_PORT)
with socket.socket(socket.AF_INET, # Internet
socket.SOCK_STREAM) as sock: # UDP
sock.connect((TCP_IP, TCP_PORT))
for i in range(10):
msg = f"Hello {i:5}"
print("Sening:", msg)
sock.send(msg.encode())
buf = sock.recv(2048)
print("Got: ", buf.decode())
sock.close()
"""
Simple tcp server, reverses the packet.
Alan Marchiori
"""
import socket
import threading
TCP_IP = "" # empty string is the default interface, all IPs
TCP_PORT = 3333
print ("TCP target IP:", TCP_IP)
print ("TCP target port:", TCP_PORT)
def handle_client(conn, addr):
while(True):
buf = conn.recv(2048)
if len(buf) == 0:
break
print(f"Recv from {addr} [{len(buf)}]: {buf.decode()}")
print(f"Send to {addr} [{len(buf)}]: {buf[::-1].decode()}")
conn.send(buf[::-1])
print( f"Disconnect from client {addr}")
conn.close()
with socket.socket(socket.AF_INET, # Internet
socket.SOCK_STREAM) as sock: # TCP
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((TCP_IP, TCP_PORT))
sock.listen()
while (True):
(conn, addr) = sock.accept()
print(f"New connection from {addr}")
threading.Thread(target=handle_client,
args=(conn, addr),
daemon=True).start()
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment