import socket import time def tcpserver(host, port, nlis=1) : sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind((host, port)) sock.listen(nlis) print('## waiting for connection at %s:%s') % (str(host), str(port)) return(sock) sock = tcpserver('localhost', 54321) conn, addr = sock.accept() print('## connected by %s:%s') % (str(addr[0]), str(addr[1])) n = 0 while True : n += 1 conn.sendall(str(n)) print(n) time.sleep(1)
import socket def tcpclient(host, port) : sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.connect((host, port)) print('## connected to %s:%s') % (str(host), str(port)) return(sock) sock = tcpclient('localhost', 54321) while True : data = sock.recv(4096) if not data : break else : print(data)