使用htonl、pack、ntohl、unpack重写send和receive函数 《Python网络编程攻略》

在利用select.select编写聊天室服务器的案例中http://blog.csdn.net/zhou8201/article/details/60866947
重写了sock的send和recv函数。

程序如下:

# Some utilities
def send(channel, *args):
    buffer = cPickle.dumps(args)
    value = socket.htonl(len(buffer))
    size = struct.pack("L",value)
    channel.send(size)
    channel.send(buffer)

def receive(channel):
    size = struct.calcsize("L")
    size = channel.recv(size)

    #socket.recv(bufsize[, flags]) 
    #Receive data from the socket. The return value is a string representing the data received.
    #The maximum amount of data to be received at once is specified by bufsize. See the Unix manual page recv(2) for the meaning of the optional argument flags; it defaults to zero.
    #Note:For best match with hardware and network realities, the value of bufsize should be a relatively small power of 2, for example, 4096.

    try:
        size = socket.ntohl(struct.unpack("L",size)[0])
        #socket.ntohl(x) 
        #Convert 32-bit positive integers from network to host byte order.
        #On machines where the host byte order is the same as network byte order, 
        #this is a no-op; otherwise, it performs a 4-byte swap operation.

    except struct.error, e:
        return ''
    buf = ""
    while len(buf) < size:
        buf += channel.recv(size - len(buf))
    return cPickle.loads(buf)[0]

各个函数的作用及每一步的结果如下图所示,它的主要作用大概是为了将主机字节序转换为网络字节序。
434513813.jpg

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值