首页 > 代码库 > Python网络编程——修改套接字发送和接收的缓冲区大小

Python网络编程——修改套接字发送和接收的缓冲区大小

很多情况下,默认的套接字缓冲区大小可能不够用。此时,可以将默认的套接字缓冲区大小改成一个更合适的值。

1. 代码

 1 # ! /usr/bin/env python 2 # -*- coding: utf-8 -*- 3  4 import socket 5  6 # 设置发送缓冲域大小 7 SEND_BUF_SIZE = 4096 8 # 设置接收缓冲域大小 9 RECV_BUF_SIZE = 409610 11 12 def modify_buff_size():13     # 创建TCP socket14     # UDP socket —— s=socket.socket(socket.AF_INET,SOCK_DGRAM)15     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)16 17     # 获取当前套接字关联的选项18     # socket.SOL_SOCKET —— 正在使用的socket选项19     # socket.SO_SNDBUF —— 发送缓冲区大小20     bsize = sock.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF)21     #打印更改前的发送缓冲区大小22     print("Buffer size [Before]: %d" % bsize)23 24     # 设置TCP套接字关联的选项25     # socket.TCP_NODELAY TCP层套接口选项26     # 1 —— 表示将TCP_NODELAY标记为TRUE27     sock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)28 29     # 设置发送缓冲域套接字关联的选项30     sock.setsockopt(31         socket.SOL_SOCKET,32         socket.SO_SNDBUF,33         SEND_BUF_SIZE)34 35     # 设置接收缓冲域套接字关联的选项36     sock.setsockopt(37         socket.SOL_SOCKET,38         socket.SO_RCVBUF,39         RECV_BUF_SIZE)40 41     # 获取设置后的发送缓冲域42     bsize = sock.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF)43     print("Buffer size [After] : %d" % bsize)44 45 if __name__ == __main__:46     modify_buff_size()

2.setsockopt()和getsockopt()

 1 def setsockopt(self, level, option, value):  # real signature unknown; restored from __doc__ 2     """ 3     setsockopt(level, option, value) 4  5     Set a socket option.  See the Unix manual for level and option. 6     The value argument can either be an integer or a string. 7     """ 8     pass 9 10 def getsockopt(self, level, option, buffersize=None):  # real signature unknown; restored from __doc__11     """12     getsockopt(level, option[, buffersize]) -> value13 14     Get a socket option.  See the Unix manual for level and option.15     If a nonzero buffersize argument is given, the return value is a16     string of that length; otherwise it is an integer.17     """18     pass19 后续添加解释

3.AF_INET和SOCK_STREAM解释

1 socket.AF_INET —— 服务器之间网络通信2 socket.SOCK_STREAM提供有序的、可靠的、双向的和基于连接的字节流,使用带外数据传送机制,为Internet地址族使用TCP。3 SOCK_STREAM类型的套接口为全双向的字节流。对于流类套接口,在接收或发送数据前必需处于已连接状 态。用connect()调用建立与另一套接口的连接,连接成功后,即可用send()和recv()传送数据。当会话结束后,调用closesocket()。带外数据根据规定用send()和recv()来接收。

4.运行结果

1 Buffer size [Before]: 655362 Buffer size [After] : 4096

 

Python网络编程——修改套接字发送和接收的缓冲区大小