当客户端和服务器在同一进程上运行时,为什么拒绝连接?

时间:2011-05-21 19:36:23

标签: python sockets networking

我在同一个进程中运行客户端和服务器时遇到问题。每当我尝试将我的客户端连接到服务器时,它都会给我这个错误:

Traceback (most recent call last):
File "dirWatch.py", line 78, in <module>
startDirWatch(sLink)
File "dirWatch.py", line 68, in startDirWatch
sC.client('/home/homer/Downloads/test.txt')
File "/home/homer/Desktop/CSC400/gsync/serverClient.py", line 15, in client
sock.connect((host,port))
File "<string>", line 1, in connect
socket.error: [Errno 111] Connection refused

这是我使用的代码,我基本上是在尝试制作文件同步程序。我是StackOverflow的新手,所以如果我没有提供更多详细信息,请原谅。这是我正在测试客户端和服务器代码的代码:

thread.start_new_thread(sC.server ,('localhost', 50001))
sC.client('/home/homer/Downloads/test.txt')

以下是客户端服务器的实际代码,它非常基本,我只是想让它们连接:

def client(filename, host = defaultHost, port = defaultPort):
    sock = socket(AF_INET, SOCK_STREAM)
    sock.connect((host,port))
    sock.send((filename + '\n').encode())

    sock.close()

def serverthread(clientsock):
    sockfile = clientsock.makefile('r')
    filename = sockfile.readline()[:-1]
    try:
        print filename

    except:
       print('Error recieving or writing: ', filename)
    clientsock.close()

def server(host, port):
    serversock = socket(AF_INET, SOCK_STREAM)
    serversock.bind((host,port))
    serversock.listen(5)
    while True:
        clientsock, clientaddr = serversock.accept()
        print('Connection made');
        thread.start_new_thread(serverthread, (clientsock,))

任何帮助或建议将不胜感激。谢谢你的阅读。

2 个答案:

答案 0 :(得分:1)

我的第一个猜测就是当客户端尝试连接时,服务器线程还没有真正开始;客户端正在连接,但没有什么是在听。创建线程并将控制权转移给它需要花费大量时间。您可以在客户端连接之前休眠,或者重试几次,或者对它有所了解并在套接字打开时让服务器线程发出信号。

答案 1 :(得分:1)

而不是处理线程同步和低级套接字怪癖(如socket.send)的麻烦,不保证发送你传递的整个字符串!),试试Twisted! / p>

以下是使用Twisted的演示版本,没有同步问题:

from twisted.internet import reactor
from twisted.internet.protocol import ServerFactory, ClientFactory
from twisted.protocols.basic import LineOnlyReceiver

class FileSyncServer(LineOnlyReceiver):
    def lineReceived(self, line):
        print "Received a line:", repr(line)
        self.transport.loseConnection()

class FileSyncClient(LineOnlyReceiver):
    def connectionMade(self):
        self.sendLine(self.factory.filename)
        self.transport.loseConnection()


def server(host, port):
    factory = ServerFactory()
    factory.protocol = FileSyncServer
    reactor.listenTCP(port, factory, interface=host)


def client(filename, host, port):
    factory = ClientFactory()
    factory.protocol = FileSyncClient
    factory.filename = filename
    reactor.connectTCP(host, port, factory)


server("localhost", 50001)
client("test.txt", "localhost", 50001)
reactor.run()