我有来自文档的代码:
#!/usr/bin/env python
import socket
TCP_IP = '192.168.1.66'
TCP_PORT = 40000
BUFFER_SIZE = 20 # Normally 1024, but we want fast response
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connection address:', addr
while True:
data = conn.recv(BUFFER_SIZE)
if not data: break
print "received data:", data
conn.send(data)
conn.close()
但是每次断开连接都会关闭,如何让它永远运行?
答案 0 :(得分:6)
尝试并更改行
if not data: break
到
if not data: continue
这种方式不是退出循环,而是等待更多数据
答案 1 :(得分:4)
您需要为每个要处理的连接拨打accept()
一次。到第一个近似值:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
while True:
conn, addr = s.accept()
print 'Connection address:', addr
while True:
data = conn.recv(BUFFER_SIZE)
if not data: break
print "received data:", data
conn.send(data)
conn.close()