VPP-659 TCP improvements
[vpp.git] / src / scripts / vnet / uri / dummy_app.py
1 #!/usr/bin/env python
2
3 import socket
4 import sys
5 import time
6
7 # action can be reflect or drop 
8 action = "drop"
9
10 def handle_connection (connection, client_address):
11     print("Received connection from {}".format(repr(client_address)))
12     try:
13         while True:
14             data = connection.recv(4096)
15             if not data:
16                 break;
17             if (action != "drop"):
18                 connection.sendall(data)
19     finally:
20         connection.close()
21         
22 def run_server(ip, port):
23     print("Starting server {}:{}".format(repr(ip), repr(port)))
24     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
25     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
26     server_address = (ip, int(port))
27     sock.bind(server_address)
28     sock.listen(1)
29     
30     while True:
31         connection, client_address = sock.accept()
32         handle_connection (connection, client_address)
33
34 def prepare_data():
35     buf = []
36     for i in range (0, pow(2, 16)):
37         buf.append(i & 0xff)
38     return bytearray(buf)
39
40 def run_client(ip, port):
41     print("Starting client {}:{}".format(repr(ip), repr(port)))
42     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
43     server_address = (ip, port)
44     sock.connect(server_address)
45     
46     data = prepare_data()
47     n_rcvd = 0
48     n_sent = len (data)
49     try:
50         sock.sendall(data)
51         
52         timeout = time.time() + 2
53         while n_rcvd < n_sent and time.time() < timeout:
54             tmp = sock.recv(1500)
55             tmp = bytearray (tmp)
56             n_read = len(tmp)
57             for i in range(n_read):
58                 if (data[n_rcvd + i] != tmp[i]):
59                     print("Difference at byte {}. Sent {} got {}"
60                           .format(n_rcvd + i, data[n_rcvd + i], tmp[i]))
61             n_rcvd += n_read
62             
63         if (n_rcvd < n_sent or n_rcvd > n_sent):
64             print("Sent {} and got back {}".format(n_sent, n_rcvd))
65         else:
66             print("Got back what we've sent!!");
67             
68     finally:
69         sock.close()
70     
71 def run(mode, ip, port):
72     if (mode == "server"):
73         run_server (ip, port)
74     elif (mode == "client"):
75         run_client (ip, port)
76     else:
77         raise Exception("Unknown mode. Only client and server supported")
78
79 if __name__ == "__main__":
80     if (len(sys.argv)) < 4:
81         raise Exception("Usage: ./dummy_app <mode> <ip> <port> [<action>]")
82     if (len(sys.argv) == 5):
83         action = sys.argv[4]
84
85     run (sys.argv[1], sys.argv[2], int(sys.argv[3]))