我观察到我不了解的Docker容器中运行python代码的行为。也许有人可以解释我的行为,并且可以告诉我 Ubuntu 18.04 上的python套接字与docker镜像 python:3.6
的区别如果我在主机上启动UDP套接字,则服务器线程将在每个接收到的数据报上解除阻塞并打印出字节。这是我所期望的行为。
如果我在docker容器中启动相同的代码,则不会解除阻塞,也不会输出到stdout。如果使用ctrl + c停止服务器,则会在中断异常之前输出输出。
更新
感谢并享受我的令人毛骨悚然的代码!
Dockerfile:服务器
FROM python:3.6
COPY . /workdir
EXPOSE 8888
WORKDIR /workdir
CMD ["./main.py"]
Dockerfile:I / O测试
FROM python:3.6
COPY . /workdir
EXPOSE 8888
WORKDIR /workdir
CMD ["./iotest.py"]
I / O测试(与UDPServer相同,但不阻塞套接字)*
import threading
class iotest(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
print("Server Thread started!")
try:
while True:
print("Test i/o")
except Exception as e:
print("Exception catched")
print(e)
finally:
print("Thread exited")
服务器:
import threading
import socket
class UDPServer(threading.Thread):
PORT = 8888
HOST = '0.0.0.0'
def __init__(self):
threading.Thread.__init__(self)
def run(self):
print("Server Thread started!")
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((UDPServer.HOST, UDPServer.PORT))
while True:
msg = s.recv(4)
print("Message received")
except Exception as e:
print("Exception catched")
print(e)
finally:
print("Thread exited, Socket closed")
s.close()
I / O测试(与UDPServer相同,但不阻塞套接字)*
import threading
class iotest(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
print("Server Thread started!")
try:
while True:
print("Test i/o")
except Exception as e:
print("Exception catched")
print(e)
finally:
print("Thread exited")
客户:
import socket
import time
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('0.0.0.0', 8888))
count = 0
errors = 0
for i in range(10):
isTime = time.time()
msg = struct.pack('!f', isTime, )
time.sleep(0.5)
try:
size_date_sent = s.send(msg)
count += 1
except Exception as identifier:
errors += 1
print(str(count) + " MSG sent.")
print(str(errors) + " errors.")
s.close()
main.py:
import UDPServer
server = UDPServer.UDPServer()
server.start()
iotest.py
import iotest
thr = iotest.iotest()
thr.start
构建并运行
docker build -t pythontest .
docker run -p 8888:8888/udp pythontest