0

currently I am the only guy in my team, who knows the C++ language. Therefore I got charged with the task to create a native tizen service for our already existing (wearable) web app.

The main purpose of the service is to receive UDP message, which are being broadcasted from a system within the same network (i.e. connected to same access point).

I've made 2 simple python scripts. The first one sends broadcast messages on button clicks:

class UDPServer(object):
    '''
        A simple UDP server with a send method.
    '''

    def __init__(self):
        '''
            Initializes the server.
        '''
        import socket
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

    def broadcast_message(self, message):
        '''
            Sends out a broadcast message.
        '''
        self.socket.sendto(message, ('<broadcast>', 3333))


class   GUI(object):
    '''
        A simple UI to use the server with.
    '''

    def __init__(self):
        '''
            Initializes the simple ui.
        '''
        import Tkinter
        self.root = Tkinter.Tk()
        self.root.title("UDP System")
        self.button = Tkinter.Button(self.root, text="Action!")
        self.button.place(x=0, y=0)
        self.button.pack(fill='x')
        self.root.update()

    def action(self, callback, *args):
        '''
            Sets the action to be performed when the button's being called.
        '''
        self.button.configure(command=lambda: callback(*args))

    def run(self):
        '''
            Invokes the message pump of the root widget.
        '''
        self.root.mainloop()

def main():
    '''
        Launches the UDP server and its ui.
    '''
    server = UDPServer()
    gui = GUI()
    gui.action(server.broadcast_message, "Hello, World!")
    gui.run()


if __name__ == '__main__':
    main()

and the latter receives those messages:

class GUI(object):
    '''
        Simple GUI for the receiver.
    '''

    def __init__(self):
        '''
            Initializes the UI.
        '''
        import Tkinter
        self.root = Tkinter.Tk()
        self.root.title("UDPReceiver")
        self.list = Tkinter.Listbox(self.root)
        self.list.pack(fill='x')

    def add_message(self, message):
        '''
            Adds an message to the listbox.
        '''
        self.list.insert(0, message)

    def run(self):
        '''
            Runs the widgets mainloop.
        '''

        self.root.mainloop()

class Receiver(object):
    '''
        Simple UDP receiver.
    '''

    def __init__(self):
        '''
            Initializes a simple udp receiver/client.
        '''
        import socket
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.socket.bind(('', 3333))

    def recv(self):
        '''
            Listens for a message and returns it.
        '''
        return self.socket.recvfrom(4096)

def main():
    '''
        Launches the udp receiver and its ui.
    '''
    gui = GUI()
    client = Receiver()

    def proc():
        '''
            A simple fetch and update routine to be run 
            in a seperate thread.
        '''
        while gui.root.state() == 'normal':
            msg = client.recv()
            gui.add_message(msg)

    from thread import start_new_thread
    start_new_thread(proc, ())
    gui.run()

if __name__ == '__main__':
    main()

Apparently both scripts are working correctly, since I am able to receive the messages issued by the other script (however, tested it only on the same PC.)

Now I am trying to implement the "listening behavior" for the native service. The application seems to work fine, without crashing. Yet it doesn't receive anything, although following code seems fine:

UDPSocket::UDPSocket()
: socket{0}
{
    addrinfo hints{0, };
    const char*     pHostname = 0;
    const char*     pPortname = "3333";
    hints.ai_family     = AF_UNSPEC;
    hints.ai_family     = SOCK_DGRAM;
    hints.ai_protocol   = 0;
    hints.ai_flags      = AI_PASSIVE | AI_ADDRCONFIG;

    addrinfo* res{nullptr};
    int err = ::getaddrinfo(pHostname, pPortname, &hints, &res);
    if(0 != err){
        throw std::runtime_error{"Failed to get address info."};
    }

    socket = ::socket(res->ai_family, res->ai_socktype, res->ai_protocol);
    if(-1 == socket){
        throw std::runtime_error{"Failed to create socket."};
    }

    int broadcast = 1;
    ::setsockopt(socket, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof(broadcast));

    err = ::bind(socket, res->ai_addr, res->ai_addrlen);
    if(-1 == err){
        throw std::runtime_error{"Failed to bind socket."};
    }

    freeaddrinfo(res);
}

UDPSocket::~UDPSocket()
{
    close(socket);
}

std::string     UDPSocket::listen() const{


    char                buffer[512];
    sockaddr_storage    src_addr;
    socklen_t           src_addr_len = sizeof(src_addr);
    ssize_t             count = ::recvfrom(socket,
                                            buffer,
                                            sizeof(buffer),
                                            0,
                                            (sockaddr*) &src_addr,
                                            &src_addr_len);

    if(-1 == count){
        throw std::runtime_error{strerror(errno)};
    } else if (count == sizeof(buffer)){
        // Issue warning
        return buffer;
    } else{
        return buffer;
    }
}

The application is running fine in the emulator, except for the fact, that the service stalls when calling "UDPSocket::listen()" - I guess it's due the fact that I am in blocking mode. It stalls and never receives anything, regardless how often I punch the send button, that floods my local network with UDP messages.

TL;DR Are there any special configuration steps required for receiving UDP messages on the Tizen Emulator?

Bonus Question: I want a method to continuously watch out for incoming UDP messages. Should I start an extra thread for the "receiver" in the service?

D. Joe
  • 1

1 Answers1

0

Ok, I fixed the problem(s). The first mistake was an autocompletion mistake:

hints.ai_socktype = SOCK_DGRAM;

instead of

hints.ai_family = SOCK_DGRAM;

The second mistake or better thing I forgot: Establish port forwarding.

For future readers: When establishing port forwarding (right click on the emulator > Settings > Network), the port must be free. If another application has already an socket bound to this port, you'll receive an error message.

D. Joe
  • 1