UDP ping

该Python脚本展示了如何创建一个UDPping客户端,它向服务器发送hello消息并测量响应时间,以及一个UDP服务器,它接收客户端消息并将它们转换为大写。服务器有随机丢弃数据包的行为,概率为4/10。
摘要由CSDN通过智能技术生成

在这里插入图片描述

#!python

from socket import *
import time
from func_timeout import func_set_timeout
import func_timeout
import sys # In order to terminate the program


clientSocket = socket(AF_INET, SOCK_DGRAM)
clientSocket.settimeout(1)
#Prepare a sever socket
serverName=''
serverPort=12000
serverName='localhost'
# serverName=raw_input('ping :')

def ping():
    clientSocket.sendto('hello'.encode(),(serverName,serverPort))
    modifiedMessage,ServerAddress = clientSocket.recvfrom(2048)
    
    
i=0
while i<10:
    i=i+1
    error=0
    try:
        print 'ping '+serverName+' in times :',
        start=time.time()
        ping()
        end=time.time()
        print format((end-start), '.3f'),'s'
    except Exception as e:
        print("Time out")
    
    
#!python
# 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(('', 12000))
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()
	# 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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值