简体   繁体   English

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

[英]Creating a client and server program with python for sending TCP and UDP packets

I have to write a client and a server program with python were the user gets ask if he would like to send via TCP or UDP. 如果用户询问他是否要通过TCP或UDP发送,我必须使用python编写客户端和服务器程序。 The Server simply sends back the data because i want to find out how long it takes (RTT). 服务器只是发回数据,因为我想找出它需要多长时间(RTT)。

How can the server detect either the client sends TCP or UPD Data? 服务器如何检测到客户端发送TCP或UPD数据?

This is just for an educational purpose, not meant to be used in production. 这仅是出于教育目的,而不是用于生产。

I have the following code so far: 到目前为止,我有以下代码:

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

and server: 和服务器:

#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()

The server will have to listen on both UDP & TCP. 服务器将必须同时监听UDP和TCP。 You can use two server processes, threads or block your server with select . 您可以使用两个服务器进程,线程或通过select阻止服务器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM