我是Python和Socket编程的新手,正在尝试编写回显客户端/服务器Socket。我已经编写了服务器程序,使得30%的数据包丢失。我编写了客户端程序,在一秒钟后超时,因为数据包可能会丢失。然而,每当我运行我的客户端Socket时,输出总是100%的“请求超时”。我认为这是因为我的服务器从未收到消息。我多次检查过我的代码,但无法找到原因。以下是我的服务器和客户端Socket代码。任何帮助将不胜感激。
服务器Socket:
# We will need the following module to generate randomized lost packets
import random
from socket import *
# Create a UDP socket
# Notice the use of SOCK_DGRAM for UDP packets
serverSocket = socket(AF_INET, SOCK_DGRAM)
# Assign IP address and port number to socket
serverSocket.bind(('', 12000))
while True:
# Generate random number in the range of 0 to 10
rand = random.randint(0, 10)
# Receive the client packet along with the address it is coming from
message, address = serverSocket.recvfrom(1024)
# Capitalize the message from the client
message = message.upper()
# If rand is less is than 4, we consider the packet lost and do notrespond
if rand < 4:
continue
# Otherwise, the server responds
serverSocket.sendto(message, address)
客户端套接字:
import time
from socket import *
pings = 1
#Send ping 10 times
while pings < 11:
#Create a UDP socket
clientSocket = socket(AF_INET, SOCK_DGRAM)
#Set a timeout value of 1 second
clientSocket.settimeout(1)
#Ping to server
message = 'test'
addr = ("127.0.0.1", 12000)
#Send ping
start = time.time()
clientSocket.sendto(message, addr)
#If data is received back from server, print
try:
data, server = clientSocket.recvfrom(1024)
end = time.time()
elapsed = end - start
print data + " " + pings + " "+ elapsed
#If data is not received back from server, print it has timed out
except timeout:
print 'REQUEST TIMED OUT'
pings = pings - 1
import *
。要么明确列出导入的模块或函数,要么只导入基础模块并在代码中使用点符号表示;这样,未来的读者(包括你自己!)将能够快速识别事物的来源。@bsa提供了其他改善代码质量的好建议。 - Ender