我在主机上有一个双端队列。通过TCP套接字接收的每个字符串都附加到此双端队列。收到每个数据后,我将打印数据和双端队列。这是代码:
from __future__ import print_function
import commands
import socket
import select
from collections import deque
host = commands.getoutput("hostname -I")
port = 5005
backlog = 5
BUFSIZE = 4096
BUFFER_SIZE = 1024
q = deque()
def read_tcp(s):
conn, addr = s.accept()
print('Connected with', *addr)
while 1:
data = conn.recv(BUFFER_SIZE)
if not data: break
print("received data:", data)
conn.send(data) # echo
if (data == 'sample.jpg'):
print("start processing")
#processP(q)
else:
print("appended")
q.append(data)
print(q)
conn.close()
def read_udp(s):
data,addr = s.recvfrom(1024)
print("received message:", data)
def run():
# create tcp socket
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
tcp.bind((host,port))
except socket.error as err:
print('Bind failed', err)
return
tcp.listen(1)
# create udp socket
udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
udp.bind((host,port))
print('***Socket now listening at***:', host, port)
input = [tcp,udp]
try:
while True:
#print("select.select")
inputready,outputready,exceptready = select.select(input,[],[], 0.1)
for s in inputready:
if s == tcp:
read_tcp(s)
elif s == udp:
read_udp(s)
else:
print("unknown socket:", s)
# Hit Break / Ctrl-C to exit
except KeyboardInterrupt:
print('\nClosing')
raise
tcp.close()
udp.close()
if __name__ == '__main__':
run()
问题是,当我打印接收到的数据并在print("received data:", data)
和print(q)
行中进行双端队列操作时,可以正确打印接收到的数据,但是在每个步骤中都像这样打印双端队列内容:< / p>
deque([''])
deque(['',''])
deque(['','',''])
怎么了?这是发件人代码,似乎没有任何问题:
from __future__ import print_function
import socket
from struct import pack
import commands
import select
#HOST = '10.0.0.2'
PORT = 5005
BUFSIZE = 4096
def tcp_send(s, ip):
TCP_IP = ip
BUFFER_SIZE = 1024
MESSAGE = s
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, PORT))
s.send(MESSAGE)
data = s.recv(BUFFER_SIZE)
s.close()
print ("sent data:", data)
fnames = [
'90.jpg','91.jpg','92.jpg','93.jpg','94.jpg','95.jpg','96.jpg','97.jpg','98.jpg','99.jpg','100.jpg','sample.jpg'
]
def main():
for fname1 in fnames:
tcp_send(fname1,'10.0.0.2')
if __name__ == '__main__':
main()
答案 0 :(得分:1)
用
替换您的read_tcpdef read_tcp(s):
conn, addr = s.accept()
print('Connected with', *addr)
while 1:
data = conn.recv(BUFFER_SIZE)
if not data: break
print("received data:", data)
conn.send(data) # echo
print(data)
if (data == 'sample.jpg'):
print("start processing")
#processP(q)
else:
print("appended", data)
q.append(data)
print(q)
conn.close()
您正在尝试访问外部数据,这就是为什么它为空
答案 1 :(得分:0)
它看起来像缩进问题。仅当对read_tcp()
求值为data
时,您才会退出while循环(在False
中)。只有这样,您才已经将循环data
的当前值附加到双端队列q
。在循环中,您将打印出每块数据。我认为if块需要缩进一级才能成为循环的一部分。
也在read_udp()
中,我看不到您要添加任何内容来填充双端队列