我在python中使用了一个简单的tcp_server。这是代码: -
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
conn, addr = s.accept()
#inputs = [conn, serial_obj]
outputs = []
#read_input.read_input(inputs,outputs)
while 1:
data = conn.recv(BUFFER_SIZE)
if not data: break
print "received data:", data
conn.send(data)
conn.close()
我的问题是,一旦收到数据,连接就被删除,我必须重新运行tcp_server程序才能启动连接。我该如何让它永远倾听。
答案 0 :(得分:1)
您需要两个嵌套的while循环。外部循环永远运行,每个传入连接一次。内部循环根据它在当前连接上接收的数据运行。试试这个:
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
while True:
conn, addr = s.accept()
#inputs = [conn, serial_obj]
outputs = []
#read_input.read_input(inputs,outputs)
while 1:
data = conn.recv(BUFFER_SIZE)
if not data: break
print "received data:", data
conn.send(data)
conn.close()