简体   繁体   English

Python-来自服务器的UDP套接字检查响应

[英]Python - UDP socket Check response from server

I have a basic client/server program. 我有一个基本的客户端/服务器程序。 The server sends a timestamp to the client. 服务器将时间戳发送给客户端。 I want to check to see if the client has responded with message and if not, resend the request. 我想检查客户端是否响应了消息,如果没有,请重新发送请求。 How would I go about this? 我将如何处理?

while 1:
    wait = "True"

    line = raw_input("Press enter to get the time or \"STOP\" to exit: ")
    if line == "STOP":
            break
    print "Waiting for response......"
    s.sendto(line, (servAddr,servPort))
    line, server = s.recvfrom(256)
    while wait:         // Obviously wrong, but pseudo 
            if line == "":
                    print 'Send another'
                    wait = False

    print (line)

It seems you need either socket.settimeout() or select module. 似乎您需要用socket.settimeout()select模块。

With .settimeout() you can tell socket to raise socket.timeout exception if it didn't receive any data within the specified timeframe. 使用.settimeout()可以告诉套接字引发socket.timeout异常,如果该套接字在指定时间范围内未收到任何数据。 This is good enough if your server only has to deal with one client (one client per thread/process/greenlet/whatever also works). 如果您的服务器只需要处理一个客户端(每个线程/进程/ greenlet /无论哪个也可以),则这已经足够了。 If you want your server to do something while waiting for client to respond and you're not using any threading/asynchronous framework, you'll probably have to write a bit more code as you'll want to set zero timeout and track the time to re-send the message manually. 如果您希望服务器在等待客户端响应时做一些事情,并且您没有使用任何线程/异步框架,则可能需要编写更多代码,因为您想将超时设置为零并跟踪时间手动重新发送消息。

select module provides you with tools to listen to multiple sockets with a common timeout. select模块为您提供了可在一个公共超时时间内监听多个套接字的工具。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM