Python网络编程——修改套接字发送和接收的缓冲区大小
很多情况下,默认的套接字缓冲区大小可能不够用。此时,可以将默认的套接字缓冲区大小改成一个更合适的值。
1. 代码
[shell]
# ! /usr/bin/env python
# -*- coding: utf-8 -*-
import socket
# 设置发送缓冲域大小
SEND_BUF_SIZE = 4096
# 设置接收缓冲域大小
RECV_BUF_SIZE = 4096
def modify_buff_size():
# 创建TCP socket
# UDP socket —— s=socket.socket(socket.AF_INET,SOCK_DGRAM)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 获取当前套接字关联的选项
# socket.SOL_SOCKET —— 正在使用的socket选项
# socket.SO_SNDBUF —— 发送缓冲区大小
bsize = sock.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF)
#打印更改前的发送缓冲区大小
print("Buffer size [Before]: %d" % bsize)
# 设置TCP套接字关联的选项
# socket.TCP_NODELAY TCP层套接口选项
# 1 —— 表示将TCP_NODELAY标记为TRUE
sock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)
# 设置发送缓冲域套接字关联的选项
sock.setsockopt(
socket.SOL_SOCKET,
socket.SO_SNDBUF,
SEND_BUF_SIZE)
# 设置接收缓冲域套接字关联的选项
sock.setsockopt(
socket.SOL_SOCKET,
socket.SO_RCVBUF,
RECV_BUF_SIZE)
# 获取设置后的发送缓冲域
bsize = sock.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF)
print("Buffer size [After] : %d" % bsize)
if __name__ == '__main__':
modify_buff_size()
[/shell]
2.setsockopt()和getsockopt()
[shell]</pre>
def setsockopt(self, level, option, value): # real signature unknown; restored from __doc__
"""
setsockopt(level, option, value)
Set a socket option. See the Unix manual for level and option.
The value argument can either be an integer or a string.
"""
pass
def getsockopt(self, level, option, buffersize=None): # real signature unknown; restored from __doc__
"""
getsockopt(level, option[, buffersize]) -> value
Get a socket option. See the Unix manual for level and option.
If a nonzero buffersize argument is given, the return value is a
string of that length; otherwise it is an integer.
"""
pass
后续添加解释
[/shell]
3.AF_INET和SOCK_STREAM解释
[shell]
<pre>1 socket.AF_INET —— 服务器之间网络通信
2 socket.SOCK_STREAM提供有序的、可靠的、双向的和基于连接的字节流,使用带外数据传送机制,为Internet地址族使用TCP。
3 SOCK_STREAM类型的套接口为全双向的字节流。对于流类套接口,在接收或发送数据前必需处于已连接状 态。用connect()调用建立与另一套接口的连接,连接成功后,即可用send()和recv()传送数据。当会话结束后,调用closesocket()。带外数据根据规定用send()和recv()来接收。
[/shell]
4.运行结果
[shell]
1 Buffer size [Before]: 65536
2 Buffer size [After] : 4096
[/shell]