2011-05-21 15 views
2

同じプロセスでクライアントとサーバーを実行する際に問題が発生しています。 、私は基本的に、ファイル同期プログラムを作成しようとしているクライアントとサーバーが同じプロセスで実行されているときに接続が拒否されるのはなぜですか?

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,)) 

すべてのヘルプまたはアドバイスをいただければ幸いです。読んでくれてありがとう。

+1

andrewdskiコメントを言い直すために 'defaultHost'と' defaultPort' – andrewdski

+1

かの値がどのようなものです:あなたのサーバがlocalhost' 'に結合しクライアントが 'localhost'に接続し、別のネットワークインターフェースに関連付けられたホスト名には接続しないのでしょうか? –

答えて

1

私の最初の推測は、クライアントが接続しようとすると、サーバスレッドがまだ実際には進まなかったことです。クライアントは接続していますが、何も聞いていません。スレッドを作成してそのスレッドに制御を移すのにはかなりの時間がかかります。クライアントが接続する前にスリープ状態にするか、何度か試してみるか、空想的な状態になり、ソケットが開いているときにサーバースレッドに信号が送られます。

1

socket.sendのようなスレッド同期と低レベルのソケットクッキーの扱いではなく、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() 
関連する問題