UDP客户端每秒发送一次ping,并打印发送给它的任何内容?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (81)

这是目前我的代码:

import socket
from time import sleep
from contextlib import contextmanager

UDP_IP_ADDRESS = "127.0.0.1"
UDP_PORT_NO = 14004
Message = b"Hello World, From Client B"


@contextmanager
def socket_ctx():
    """ Context Manager for the socket. Makes sure the socket will close regardless of why it exited."""
    my_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    # Assign IP address and a RANDOM available port number to socket
    my_socket.bind(('127.0.0.1', 0))
    try:
        # Let the rest of the app use the socket and wait for it to finish
        yield my_socket
    finally:
        my_socket.close()


def send_data(client_sock):
    client_sock.sendto(Message, (UDP_IP_ADDRESS, UDP_PORT_NO))


def listen(client_sock):
    print(client_sock.recvfrom(100))



with socket_ctx() as sock:
    while True:
        send_data(sock)
        listen(sock)
        sleep(2)

目前,它发送一次ping,然后只是闲置,因为它可能正在监听。如果确实发生了ping回,比如说,另一个客户端向服务器发送一个ping命令,并且服务器向该客户端发送ping命令,它会听到并打印它,然后再次启动该循环。

提问于
用户回答回答于

代码:

import socket
import select
import time

UDP_IP_ADDRESS = "127.0.0.1"
UDP_PORT_NO = 14004
Message = b"Hello World, From Client B"

udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp_socket.bind(('127.0.0.1', 0))
print "UDP socket is listening for incoming packets on port", udp_socket.getsockname()[1]

# When we want to send the next periodic-ping-message out
nextPingTime = time.time()

while True:
   secondsUntilNextPing = nextPingTime - time.time();
   if (secondsUntilNextPing < 0):
      secondsUntilNextPing = 0

   # select() won't return until udp_socket has some data
   # ready-for-read, OR until secondsUntilNextPing seconds 
   # have passed, whichever comes first
   inReady, outReady, exReady = select.select([udp_socket], [], [], secondsUntilNextPing)

   if (udp_socket in inReady):
      # There's an incoming UDP packet ready to receive!
      print(udp_socket.recvfrom(100))

   now = time.time()
   if (now >= nextPingTime):
      # Time to send out the next ping!
      print "Sending out scheduled ping at time ", now
      udp_socket.sendto(Message, (UDP_IP_ADDRESS, UDP_PORT_NO))
      nextPingTime = now + 1.0   # we'll do it again in another second

扫码关注云+社区

领取腾讯云代金券