使用python创建客户端和服务器程序以发送TCP和UDP数据包

时间:2013-04-24 17:56:13

标签: python sockets tcp udp

我必须用python写一个客户端和一个服务器程序,如果用户想要通过TCP或UDP发送,就会询问它。服务器只是发送回数据,因为我想知道它需要多长时间(RTT)。

服务器如何检测客户端发送TCP或UPD数据?

这仅用于教育目的,并非用于生产。

到目前为止,我有以下代码:

client.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()

1 个答案:

答案 0 :(得分:1)

服务器必须同时监听UDP和TCP。您可以使用两个服务器进程,线程或使用select阻止您的服务器。