python socket问题


问题1 : recv返回值不定长,超出设定值问题。

socket.setblocking(flag) 
Set blocking or non-blocking mode of the socket: if flag is 0, the socket is set to non-blocking, else to blocking mode. Initially all sockets are in blocking mode. In non-blocking mode, if a recv() call doesn’t find any data, or if a send() call can’t immediately dispose of the data, a error exception is raised; in blocking mode, the calls block until they can proceed. s.setblocking(0) is equivalent to s.settimeout(0); s.setblocking(1) is equivalent to s.settimeout(None). 


问题2:非阻塞的socket  [Errno 11] Resource temporarily unavailable 错误问题解决

  当客户通过Socket提供的send函数发送大的数据包时,就可能返回一个EGGAIN的错误。该错误产生的原因是由于send 函数中的size变量大小超过了tcp_sendspace的值。tcp_sendspace定义了应用在调用send之前能够在kernel中缓存的数据量。当应用程序在socket中设置了O_NDELAY或者O_NONBLOCK属性后,如果发送缓存被占满,send就会返回EAGAIN的错误。

  为了消除该错误,有三种方法可以选择:
  (1)调大tcp_sendspace,使之大于send中的size参数
  ---no -p -o tcp_sendspace=65536

  (2)在调用send前,在setsockopt函数中为SNDBUF设置更大的值

默认的socket选项不够用的时候,就必须要使用setsockopt来调整。就是使用setsockopt。

socket.setsockopt(level,optnamevalue)

Set the value of the given socket option (see the Unix manual pagesetsockopt(2)). The needed symbolic constants are defined in thesocketmodule (SO_* etc.). The value can be an integer or a string representing a buffer. In the latter case it is up to the caller to ensure that the string contains the proper bits (see the optional built-in modulestruct for a way to encode C structures as strings).

有三个参数:

level:选项定义的层次。支持SOL_SOCKET、IPPROTO_TCP、IPPROTO_IP和IPPROTO_IPV6。

optname:需设置的选项。

value:设置选项的值。


  (3)使用write替代send,因为write没有设置O_NDELAY


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值