Opticmountain
Opticmountain

Reputation: 63

Re-broadcasting a UDP stream with python

I am running a simple closing socket listener to ingest a UDP stream containing json directed to port 5001 (in this instance) on localhost:

import socket
import json

from contextlib import closing

def monitor_stream():
    with closing(socket.socket(socket.AF_INET, socket.SOCK_DGRAM)) as s:

        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.bind(('', 5001))

        while True:

            data, addr = s.recvfrom(4096)

            try:
                data = data.decode('ascii')
                data = json.loads(data)
            except:
                print 'Not valid JSON: ', data
    

I need to re-broadcast the stream to another local port (arbitrarily 5002 in this example) so that a second program can access the data in as near as real time. Low latency is crucial. Is the following (using socket.sendto() within the while) an acceptable method:

        while True:

            data, addr = s.recvfrom(4096)
           
            s.sendto(data, ('localhost', 5002))

If not, how else might I achieve the same result?

I have assumed that there is no way of multiple programs ingesting the original stream in a simultaneous fashion as they originate as unicast packets so only the first bound socket receives them.

Secondly, how might I cast the same stream to multiple ports (local or not)?

I am unable to change the incoming stream port / settings.

Upvotes: 0

Views: 640

Answers (1)

Opticmountain
Opticmountain

Reputation: 63

This was a simple misuse of socket.sendto() which can only be called on a non-connected socket.

I was trying to use the bound-listener to send-on the ingested stream.

I seems you need two socket objects to re-broadcast to a different address. The second socket is an un-bound echo client as the address is specified in .sendto(string, address)

Upvotes: 1

Related Questions