Skip to main content

udpsocket.close()

Close an open UDP socket

Availability

Device (from impOS™ 42)

Returns

Nothing

Description

This method closes an open UDP socket. Once closed, the target udpsocket object is unavailable for use and if any of its methods are called, an exception will be thrown. The method will have no effect if it is called on a udpsocket object that has already been closed. It is called implicitly if the udpsocket object goes out of scope.

Once a UDP socket is closed, its port, if it was bound to one, is now free for use by other UDP sockets.

Example

local interface;
local udpsocket;

function interfaceHandler(state) {
    // Called when the local networking interface state changes
    server.log("Connection state: " + state);

    if (state == imp.net.CONNECTED && udpsocket == null) {
        // We're connected, so initiate UDP
        server.log("Opening UDP on local network");
        udpsocket = interface.openudp(null, 20001);
    } else if (imp.net.WIFI_STOPPED && udpsocket != null) {
        // The WiFi network has gone, so close the UDP socket and
        // set it to be ready for reconnection
        server.log("Closing UDP");
        udpsocket.close();
        udpsocket = null;
    }
}

// Open the WiFi connection for local use
server.log("Opening WiFi for local networking");
interface = imp.net.open({"interface":"wl0"}, interfaceHandler);