IoT user
IoT user

Reputation: 1300

Python UDP server running in Docker container

I would like to test a simple UDP server in Docker before continue with the develop. I've never worked with Docker before so I assume it should be a beginner error

What I have currently?

The server

import threading
import socketserver



class ThreadedUDPRequestHandler(socketserver.BaseRequestHandler):

    def handle(self):
        data = self.request[0].strip()
        current_thread = threading.current_thread()
        print("Thread: {} client: {}, wrote: {}".format(current_thread.name, self.client_address, data))
        Split = threading.Thread(target=ParseIncomingData,args=(data,))
        Split.start()



class ThreadedUDPServer(socketserver.ThreadingMixIn, socketserver.UDPServer):
    pass

def publish_messages(data):
    """Publishes multiple messages to a Pub/Sub topic."""
    print('Published {} .'.format(data))

def ParseIncomingData(message):
    sender = threading.Thread(target=publish_messages, args=(message,))
    sender.start()


if __name__ == "__main__":
    HOST, PORT = "0.0.0.0", 6071
    try:
        serverUDP = ThreadedUDPServer((HOST, PORT), ThreadedUDPRequestHandler)
        server_thread_UDP = threading.Thread(target=serverUDP.serve_forever)
        server_thread_UDP.daemon = True
        server_thread_UDP.start()
        serverUDP.serve_forever()
    except (KeyboardInterrupt, SystemExit):
        serverUDP.shutdown()
        serverUDP.server_close()
        exit()

The dockerfile

# Use an official Python runtime as a base image
FROM python:3.7.2-slim

# Set the working directory to /app
WORKDIR /app

# Copy the current directory contents into the container at /app
ADD . /app

# Make port 6071 available outside this container
EXPOSE 6071/udp

# Run app.py when the container launches
CMD ["python", "app.py"]

How I execute the container?

docker run --rm -p 6071:6071/udp listener

I have tried with several combinations about the usage of the port but I don't see anything when I run it (Windows)

EXTRA:

To test the server I'm using hercules to send the USP data:

hercules

Upvotes: 1

Views: 2228

Answers (1)

IoT user
IoT user

Reputation: 1300

It works with this configuration:

Using unbuffered output in dockerfile with

CMD ["python","-u","main.py"]

Upvotes: 3

Related Questions