绝对新手在这里,我似乎无法找到我的问题的答案。运行python 2.7。现有的连接被远程主机强制关闭(简单的UDP客户端服务器)
我的服务器代码如下:
#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%,这是胜负我每次运行服务器文件,然后将时间客户端文件。防火墙开启或关闭时也是如此。我有一种感觉,这与例外情况有关,但我无法完全理解为什么。
在我的机器上工作正常,无论是在Windows 8和Linux 3.4上。 – phihag
鉴于UDP不是面向连接的,所以错误消息没有意义。这可能是一个问题发生在不同的层面(例如在一些可以被破解的防火墙逻辑中)并且被错误地报告。 –