2016-04-09 13 views
0

私は2つのホスト間のコマンドプロンプトチャットをセットアップしようとしています。入力と印刷を同時に行うには、threadingを使用しています。一つのPCは、次のコードでサーバーとして設定されていますスレッドとPythonを使用してサーバーとクライアントのチャット

def recvfun(): 
    for i in range(5): 
     print c.recv(1024) 
    return 

def sendfun(): 
    for i in range(5): 
     c.send(raw_input()) 
    return 

s = socket.socket()   # Create a socket object 
host = socket.gethostname() # Get local machine name 
port = 12345    # Reserve a port for your service. 
s.bind((host, port))  # Bind to the port 
s.listen(5)     # Now wait for client connection. 
c, addr = s.accept()  # Establish connection with client. 
print 'Got connection from', addr 

try: 
    Thread(target = recvfun, args = []).start() 
    Thread(target = sendfun, args = []).start() 
except Exception,errtxt: 
    print errtxt 

c.close()     # Close the connection 

そして、他のPCには、次のようなコードで設定されています。私は、クライアントとサーバーの両方を実行している現時点で

s = socket.socket()   # Create a socket object 
host = socket.gethostname() # Get local machine name 
port = 12345    # Reserve a port for your service. 
host = "192.168.1.111" 
s.connect((host, port)) 

try: 
    Thread(target = recvfun, args = []).start() 
    Thread(target = sendfun, args = []).start() 
except Exception,errtxt: 
    print errtxt 

s.close      # Close the socket when done 

同じマシン上で、2つのコマンドプロンプトを表示します。しかし、私はテキストを送信または受信しようとするたびに、私は、サーバーのコマンドプロンプトで次のエラーログを取得しています:

Got connection from ('192.168.1.111', 25789) 
hi 
Exception in thread Thread-2: 
Traceback (most recent call last): 
    File "C:\Python27\lib\threading.py", line 810, in __bootstrap_inner 
    self.run() 
    File "C:\Python27\lib\threading.py", line 763, in run 
    self.__target(*self.__args, **self.__kwargs) 
    File "C:\Python27\programs\server.py", line 12, in sendfun 
    c.send(raw_input()) 
    File "C:\Python27\lib\socket.py", line 170, in _dummy 
    raise error(EBADF, 'Bad file descriptor') 
error: [Errno 9] Bad file descriptor 

あなたのいずれかが、私はこのエラーを取得していますし、それを解決できるか、なぜ私が理解するのに役立ちてもらえ。

ありがとうございます!

答えて

1

スレッドは、コードの入力を開始すると同時に、メインプログラムが実行を継続している間にすぐにソケットまたは接続を閉じるため、データの送信やエラーの原因となります。何かを閉じる前にスレッドが終了するのを待たなければなりません。 closeコールを削除するだけでこれを実証できます。

+0

ありがとうございます!今それは働いている。スレッドが終了するのを待ってからプログラムを終了する方法を教えてください。 – akhilc

+0

Google「pythonがスレッド終了を待つ」 –

関連する問題