这里绝对是新手,我似乎无法找到我的问题的答案。运行 python 2.7。
我的服务器代码如下:
#UDPPingerClient.py
from socket import *
#Create a UDP socket
clientSocket = socket(AF_INET, SOCK_DGRAM)
#Assign IP address and port number to socket
clientSocket.bind(("127.0.0.1",9501))
#Set a timeout value of 1 second
clientSocket.settimeout(1)
msg = "test"
#the server info
sIP = "127.0.0.1"
sPort = 12007
addr = (sIP,sPort)
a = 10
# the server will automatically drop some messages
# so we send 10 to make sure it gets there and then
# listen for a response from the server
while a > 0:
clientSocket.sendto(msg,addr)
try:
received, server = clientSocket.recvfrom(1024)
print received
except timeout:
print ('an error occured')
a = a - 1
服务器代码:
# UDPPingerServer.py
# 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(("127.0.0.1", 12007))
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()
12 # If rand is less is than 4, we consider the packet lost and do not respond
if rand < 4:
continue
# Otherwise, the server responds
serverSocket.sendto(message, address)
到目前为止,我还没有得到服务器的回复。我能够完成的最多是在收到此错误之前发送一次并超时:
an error occured <-- output from exception
Traceback (most recent call last):
File "C:/Python27/UDPPingerClient.py", line 23, in <module>
received, server = clientSocket.recvfrom(1024)
error: [Errno 10054] An existing connection was forcibly closed by the remote host
这个的重现性是 100%,这是我每次运行服务器文件和客户端文件时的结果。打开或关闭防火墙也是如此。我觉得这与例外有关,但我不能完全理解为什么。