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


你可能感兴趣的:(python,python)