我有一个项目,该线程的主线程正在请求输入。我有一个生成的接受客户端的线程,然后一旦它接受一个客户端,它将生成另一个线程以监听该套接字。但是,问题是客户端连接后或发送了某些内容后,我的命令提示符没有回来。
import socket
import _thread
from cmd2 import *
def grab_data(conn):
while True:
try:
data = conn.recv(1024)
print(data)
except:
print("disconnected.")
break
def grab_client(sock):
while True:
conn, addr = sock.accept()
print("New connection")
_thread.start_new_thread(grab_data, (conn,))
def start_conn(ip, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((ip, int(port)))
sock.listen(10)
print("Socket listening")
_thread.start_new_thread(grab_client, (sock,))
class CLI(Cmd):
def __init__(self):
Cmd.__init__(self)
self.prompt = "Prompt> "
def do_listen(self, arg):
start_conn('0.0.0.0', '4446')
def emptyline(self):
pass
def do_quit(self, arg):
return True
cli = CLI()
cli.cmdloop("Welcome to the server.")
这是我得到的输出。
Welcome to the server.
Prompt> listen
Socket listening
Prompt> New connection
_
我期望得到的是
Welcome to the server.
Prompt> listen
Socket listening
Prompt> New connection
Prompt> _
另一个例子:
Welcome to the server.
Prompt> listen
Socket listening
Prompt> New connection
b'hey\n'
b'how\n'
b'are\n'
b'you\n'
预期:
Welcome to the server.
Prompt> listen
Socket listening
Prompt> New connection
Prompt> b'hey\n'
Prompt> b'how\n'
Prompt> b'are\n'
Prompt> b'you\n'