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

  • Post author:
  • Post category: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



版权声明:本文为zhou8201原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。