使用socket.makefile从socket读取读取错误

时间:2013-04-09 09:34:13

标签: python sockets client

我遇到了麻烦,我不知道发生了什么。 我正在使用python中的unix套接字编写一个小客户端 - 服务器应用程序。我想通过此连接发送的命令都使用换行符完成。然后我决定使用socket.makefile('r')来使用类似文件的套接字。

问题是,如果我尝试发送超过8k字节数据的行,则服务器无法读取它。我检查过,如果不使用makefile,我使用socket.recv(65560)服务器正常工作。

但我想知道为什么会这样。 提前谢谢。

要测试的代码很少:

#!/usr/bin/env python
import threading
import socket
import errno
import time
import os
import sys
import signal
datalines = []
dat6 = "A" * 6144 + "\n" #6k
dat7 = "B" * 7168 + "\n" #7k
dat8 = "C" * 8192 + "\n" #8k
dat10 = "D" * 10240 + "\n" #10k
dat16 = "E" * 16364 + "\n" #16k

datalines.append(dat6)
datalines.append(dat7)
datalines.append(dat8)
datalines.append(dat10)
datalines.append(dat16)


ev = threading.Event()
unixsocket="/tmp/socket.sock"
def runServer():
    if os.path.exists(unixsocket):
        os.remove(unixsocket)
    server = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
    server.bind(unixsocket)
    sockfile = server.makefile('r')
    print "Listening..."
    while not ev.isSet():
        for line in sockfile:
            print "RCV: %s"%line

def runClient():
    clientsocket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
    clientsocket.connect(unixsocket)
    print "Conected"
    for line in datalines:
        print "Sending data....%s" % line[0]
        clientsocket.sendall(line)


def main():
    print "Testing makefile sockets with a big mesagge to send"
    #Create a unix socket server and a client socket server
    #Send two messages from the client, and see the server response.
    server = threading.Thread(target=runServer,args=())
    client = threading.Thread(target=runClient,args=())
    print "Run server ..."
    server.start()
    print "Waiting for the client"
    time.sleep(2)
    print "Start the client"
    client.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print "Bye!!!"
        ev.set()
        #Abrupt termination
        os.kill(os.getpid(), signal.SIGKILL)


if __name__  == "__main__":
    print "Running tests..."
    main()

0 个答案:

没有答案