大家好,感谢你们审阅我的问题!
我是python的新手,按照我从一本书中学到的教程编写一个tcpserver
现在它是为python2.x编写的,我知道我应该在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()现在,当我在Python2.7.x上运行它时,这段代码失败了,它给了我一个无效的语法%,所以我修改了一些行来支持.format,因为从我在谷歌上找到的信息来看,% it已经被支持了!
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循环不执行,所以它在一秒钟后就中断了.py,所以我不能用我的tcp client script测试the tcp server script
有人能告诉我我哪里出问题了吗?
发布于 2017-02-10 21:32:23
您应该在函数的外部启动线程。如果您注意到标识,那么while循环是handle_client的一部分,因此您可以看到脚本在输出"Listning on.....“时立即退出。
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()https://stackoverflow.com/questions/42155023
复制相似问题