我一直在尝试在python中编写upd客户端和服务器。我在这里提供了我的代码。当我运行客户端和服务器文件时,我没有收到任何错误消息,我也没有得到任何输出。我做了很多研究,但我似乎无法弄清楚如何让它发挥作用。请帮忙!
我的服务器代码在这里
from socket import *
import random
def main():
Ssocket = socket(AF_INET, SOCK_DGRAM )
Ssocket.bind(('', 2014))
print("I will be waiting on port" , 2014)
while True:
RandNum = random.randint(0,10)
data , clientAddress = Ssocket.recvfrom(1024)
newData = data.upper()
if randNum < 4:
print ("packet lost")
continue
Ssocket.sendto(newData, clientAddress)
main()
我的客户端代码在
之下from socket import*
from datetime import datetime
from time import time
def main():
print (" the program is running ")
serverName = 'localhost'
port = 2014
Csocket = socket(socket.AF_INET, socket.SOCK_DGRAM)
data = ' ping'
#data = input("Enter a message in lowercase")
LastPing = 10
count = 0
Csocket.settimeout(1)
print ("Attempting to send " , count , "messages" )
while count < LastPing:
count = count + 1
startTime = time.time()
print("The current time is: " , startTime , " and this is message
number: " , count)
Csocket.sendto(data, (serverName, port))
try:
newData, clientAddress = Csocket.recvfrom(1024)
RTT = ((time.time()) - startTime)
print (newData)
print (RTT)
except socket.timeout:
print(" Request timed out ")
print ("the program is done")
答案 0 :(得分:0)
修改服务器代码和客户端代码,如下所示: Server.py
from socket import *
import random
def main():
ssocket = socket(AF_INET, SOCK_DGRAM )
ssocket.bind(('', 2014))
print("I will be waiting on port" , 2014)
while True:
RandNum = random.randint(0,10)
data , clientAddress = ssocket.recvfrom(1024)
newData = data.upper()
if RandNum < 4:
print ("packet lost")
continue
ssocket.sendto(newData, clientAddress)
main()
Client.py
from socket import *
import datetime
import time
def main():
serverName = 'localhost'
port = 2014
Csocket = socket(AF_INET, SOCK_DGRAM)
data = ' ping'
#data = input("Enter a message in lowercase")
LastPing = 10
count = 0
Csocket.settimeout(1)
print ("Attempting to send " , count , "messages" )
while count < LastPing:
count = count + 1
startTime = time.time()
print("The current time is: " , startTime , " and this is message number: " , count)
Csocket.sendto(data, (serverName, port))
try:
newData, clientAddress = Csocket.recvfrom(1024)
RTT = ((time.time()) - startTime)
print (newData)
print (RTT)
except timeout:
print(" Request timed out ")
except Exception as e:
print e
print ("the program is done")
main()
答案 1 :(得分:0)
最终通过卸载我的python和pyscripter来解决它,因为部分问题是因为我使用的是python gui和一个非对应的pyscripter。然后我安装了python 2.7.5和pyscripter 2.5.3。在pyscripter中运行服务器,在python shell中运行客户端。为我工作得很好!