远程主机强制关闭现有连接(简单UDP客户端 - 服务器)

时间:2013-10-12 21:44:00

标签: python udp

绝对的新手在这里,我似乎无法找到我的问题的答案。运行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%,这是每次运行服务器文件然后运行客户端文件时的结果。打开或关闭防火墙也是如此。我有一种感觉,这与异常有关,但我无法完全理解为什么。

1 个答案:

答案 0 :(得分:0)

这是我得到的输出:

foggy@dew ~ $ python UDPPingerClient.py 
TEST
TEST
an error occured
TEST
TEST
TEST
an error occured
TEST
an error occured
TEST
正好十条消息,有些已经超时其他人被传回去了。 除了在服务器上的额外12个rand行之外(并且不打扰解释器)我没有看到代码有任何问题。