python socket recvfrom 超时捕获,处理python套接字中的超时错误

本文介绍了如何在Python中使用socket模块处理超时错误。通过示例代码展示了如何在使用socket.sendto和socket.recvfrom时设置超时,并在发生socket.timeout异常时进行捕获。讨论了从socket导入所有内容和导入特定功能的差异,建议使用更明确的导入方式以避免命名冲突。
摘要由CSDN通过智能技术生成

I am trying to figure out how to use the try and except to handle a socket timeout.

from socket import *

def main():

client_socket = socket(AF_INET,SOCK_DGRAM)

client_socket.settimeout(1)

server_host = 'localhost'

server_port = 1234

while(True):

client_socket.sendto('Message',(server_host,server_port))

try:

reply, server_address_info = client_socket.recvfrom(1024)

print reply

except socket.Timeouterror:

#more code

The way I added the socket module was to import everything, but how do I handle exceptions in the docs it says you can use socket.timeouterror, but that doesn't work for me. Also, how would I write the try exception block if I did import socket? Can someone also explain the difference in the imports.

解决方案from foo import *

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值