2017-02-10 7 views
0

こんにちは皆さん、ありがとうございました!python tcpserver dont loop

私は、Pythonに新たなんだと私は今、それはPython 2.xのために書かれていますtcpserver

を行うことで、株式だと私は、私は3のためにそれを行う必要があります知っている私は枝本からチュートリアルを以下に示します。 xしかし、私はそれが本に説明されている方法を実行して開始したい!

これはプレーンなTCPサーバのための彼のコードです:

import socket 
import threading 

bind_ip = "0.0.0.0" 
bind_port = 9999 

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 

server.bind((bind_ip,bind_port)) 

server.listen(5) 

print "[*] Listning on %s:%d" % (bind_ip,bind_port) 

#this is our client-handling thread 
def handle_client(client_socket): 

    #print out what the client sends 
    request = client_socket.recv(1024) 

    print "[*] Recived: %s" % request 

    #send back a packet 
    client_socket.send("ACK!") 

    client_socket.close() 

    while True: 

     client,addr = server.accept() 

     print "[*] Accepted connection from: %s:%d" % (addr[0],addr[1]) 

    #spin up our client thread to handle incomming data 

    client_handler = threading.Thread(target=handle_client,args=(client,)) 
    client_handler.start() 

今、このコードは、私が私に無効な構文% を与えるのpython 2.7.35からそれを実行するときに、私がサポートするために、線の一部を変更失敗私が見つけたものからもうサポートされている。

print "[*] Listning on {0}:{1}".format(bind_ip,bind_port) 
print "[*] Recived: {0}".format(request) 
print "[*] Accepted connection from: {0}:{1}".format(addr[0],addr[1]) 

私は今それを実行したときに、それが吐き出す:[*] Listning on 0.0.0.0:9999 偉大な権利を?いいえ何らかの理由で私はwhileループが実行されないことを知ることができないので、1秒後に.pyから壊れてしまいますので、私はテストできません。tcp client script

私は、間違ってる?

+0

はトレースバックとの完全なエラーメッセージを表示します。また、 'format'がそれを行う新しい方法であっても、 '%'フォーマットはまだサポートされています。 –

+0

あなたの時間を無駄にして申し訳ありません問題は私の行間です私は大文字小文字を区別しないphpでプログラムを大括弧で囲みます – Ghostetr

答えて

0

この関数のスレッド側を開始する必要があります。あなたはインデントを注意している場合、whileループがhandle_clientの一部であり、したがって、あなたは、すぐに印刷などのスクリプトの終了を参照してください「のListning .....」

def handle_client(client_socket): 
    #Function defnition 
while True: 

     client,addr = server.accept() 

     print "[*] Accepted connection from: %s:%d" % (addr[0],addr[1]) 
     client_handler = threading.Thread(target=handle_client,args=(client,)) 
     client_handler.start()