1.test_topology.py
#!/usr/bin/python from mininet.topo import Topo, SingleSwitchTopo from mininet.net import Mininet from mininet.log import lg, info from mininet.cli import CLI def main(): lg.setLogLevel('info') net = Mininet(SingleSwitchTopo(k=2)) net.start() h1 = net.get('h1') h2 = net.get('h2') s1 = net.get('s1') net.addLink(h1, s1) h1.setIP('10.0.1.1', intf='h1-eth0') h1.setIP('10.0.1.2', intf='h1-eth1') h2.setIP('10.0.1.3', intf='h2-eth0') CLI( net ) net.stop() if __name__ == '__main__': main()
2.server.py
import socket, argparse def recvall(filename, sock, delimiter): file_ = open(filename, 'wb') recvd_bytes = 0 data = b'' while True: more = sock.recv(1024) data += more if data[-4:] == delimiter: break data = data[-10:] file_.write(more) file_.flush() file_.close() def server(ip, port, filename): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind((ip, port)) sock.listen(10) print('Listening at', sock.getsockname()) while True: sc, sockname = sock.accept() print('We have accepted a connection from', sockname) print(' Socket name:', sc.getsockname()) print(' Socket peer:', sc.getpeername()) recvall(filename, sc, b'bye$') sc.sendall(b'Thank you$') sc.close() print(' Reply sent, socket closed') if __name__ == "__main__": parser = argparse.ArgumentParser(description='Send and receive over TCP') parser.add_argument('host', help='interface the server listens at;' ' host the client sends to') parser.add_argument('-p', metavar='PORT', type=int, default=1060, help='TCP port (default 1060)') args = parser.parse_args() server(args.host, args.p, "server_recvd.mkv")
3.client.py
import socket, argparse def recvall(sock, delimiter): data = b'' while True: more = sock.recv(1) if more == delimiter: break data += more return data def client(c_ip, s_ip, filename): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind((c_ip, 1060)) print('Client has been assigned socket name', sock.getsockname()) sock.connect((s_ip, 1060)) in_file = open(filename, 'rb') block_size = 32 snd_bytes = 0 while True: piece = in_file.read(block_size) snd_bytes += block_size print('\r %d bytes send' % (snd_bytes,), ) if piece == "": piece = b'bye$' sock.sendall(piece) break # end of file sock.sendall(piece) in_file.close() message = recvall(sock, b'$') print (message) sock.close() if __name__ == "__main__": parser = argparse.ArgumentParser(description='Send and receive over TCP') parser.add_argument('-c_ip') parser.add_argument('-s_ip') args = parser.parse_args() client(args.c_ip, args.s_ip, "client_send.mkv")
4.传输文件名:client_send.mkv,运行环境python3。