如果用户询问他是否想通过 TCP 或 UDP 发送,我必须用 python 编写一个客户端和一个服务器程序。服务器只是发回数据,因为我想知道需要多长时间(RTT)。
服务器如何检测客户端发送 TCP 或 UPD 数据?
这仅用于教育目的,不打算用于生产。
到目前为止,我有以下代码:
客户端.py
import socket
numerofpackets = int(raw_input("How many packets should be sent?\n> "))
connectiontype = raw_input("TCP or UDP?\n> ")
hostname = 'localhost'
i = 0
if connectiontype != "TCP" and connectiontype != "UDP":
print "Input not valid. Either type TCP or UDP"
else:
if connectiontype == "TCP":
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((hostname, 50000))
while i < numerofpackets:
start_time = time.time()
s.send('tcp')
response = s.recv(1024)
print time.time() - start_time
i = i + 1
s.close()
elif connectiontype == "UDP":
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while i < numerofpackets:
start_time = time.time()
s.sendto('udp', (hostname, 50000))
response, serverAddress = s.recvfrom(1024)
print time.time() - start_time
i = i + 1
s.close()
和服务器:
#for tcp
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("", 50000))
s.listen(1)
while True:
komm, addr = s.accept()
data = komm.recv(1024)
komm.send(data)
s.close()
#for udp
sudp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sudp.bind(("", 50000))
while True:
daten, addr = sudp.recvfrom(1024)
s.sendto(daten, addr)
s.close()