![](/img/trans.png)
[英]TCP Server (Java) not receiving Packets from TCP Client (Python)
[英]Creating a client and server program with python for sending TCP and UDP packets
如果用户询问他是否要通过TCP或UDP发送,我必须使用python编写客户端和服务器程序。 服务器只是发回数据,因为我想找出它需要多长时间(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()
服务器将必须同时监听UDP和TCP。 您可以使用两个服务器进程,线程或通过select阻止服务器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.