2013-10-12 23 views
0

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

+0

在我的机器上工作正常,无论是在Windows 8和Linux 3.4上。 – phihag

+0

鉴于UDP不是面向连接的,所以错误消息没有意义。这可能是一个问题发生在不同的层面(例如在一些可以被破解的防火墙逻辑中)并且被错误地报告。 –

回答

0

这是输出我得到:

[email protected] ~ $ python UDPPingerClient.py 
TEST 
TEST 
an error occured 
TEST 
TEST 
TEST 
an error occured 
TEST 
an error occured 
TEST 

正好十个消息,一些人timeouted其他人回传。 除了额外的12上面的兰德线在服务器(并没有打扰解释器)我没有看到任何错误的代码。

+0

请尝试进一步调查该错误代码。这可能是网络相关的问题,那就是你的udp信息。这是一个Linux在这里顺便说一句。 – FoggyDew

+0

谢谢,我想这只是确认错误存在于python之外。[This guy](http://stackoverflow.com/questions/15734219/simple-python-udp-server-trouble-receiving-packets-from -clients-other-loca)有同样的问题,我运行他的代码。 – cancub

+0

请尝试注释掉这两行服务器中的'if rand:<4 continue',因为你没有接种prng,如果你的系统的某个方式是borked,可能导致服务器总是断开连接。 – FoggyDew

相关问题