1

我遇到了麻烦,我不知道发生了什么。我正在使用 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()
4

0 回答 0