Sunday, November 1, 2026
HomeiOS Developmentpython - Connecting To A Socket and Listening In Swift

python – Connecting To A Socket and Listening In Swift

[ad_1]

I’m attempting to implement an iOS swift device for amassing data from community gadgets. Figuring out the multicast deal with and port, I can bind and obtain the data that is being transmitted from the community {hardware}, comparable to serial information and producer and so on.

I’ve a working prototype of the device in python, which opens a socket on a multicast deal with (and port) and them prints what it receives.

Which appears like this:

MCAST_GRP = '239.255.255.250'
MCAST_PORT = 37020
IS_ALL_GROUPS = False

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if IS_ALL_GROUPS:
    # on this port, receives ALL multicast teams
    sock.bind(('', MCAST_PORT))
else:
    # on this port, pay attention ONLY to MCAST_GRP
    sock.bind((MCAST_GRP, MCAST_PORT))
mreq = struct.pack("4sl", socket.inet_aton(MCAST_GRP), socket.INADDR_ANY)

sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)



whereas True:
  information, (ip, port) = sock.recvfrom(4096)
  print (ip,port)
  print(information)

My try at implementing this in swift appears like this (made up of snippets I’ve discovered on-line):

import UIKit
import Community

class ViewController: UIViewController {

    var connection: NWConnection?
    var hostUDP: NWEndpoint.Host = "239.255.255.250"
    var portUDP: NWEndpoint.Port = 37020

    override func viewDidLoad() {
        tremendous.viewDidLoad()

        // Hack to attend till all the things is about up
        var x = 0
        whereas(x<1000000000) {
            x+=1
        }
        connectToUDP(hostUDP,portUDP)
    }

    func connectToUDP(_ hostUDP: NWEndpoint.Host, _ portUDP: NWEndpoint.Port) {
        // Transmited message:
        let messageToUDP = "Take a look at message"

        self.connection = NWConnection(host: hostUDP, port: portUDP, utilizing: .udp)

        self.connection?.stateUpdateHandler = { (newState) in
            print("That is stateUpdateHandler:")
            swap (newState) {
                case .prepared:
                    print("State: Readyn")
                case .setup:
                    print("State: Setupn")
                case .cancelled:
                    print("State: Cancelledn")
                case .getting ready:
                    print("State: Preparingn")
                default:
                    print("ERROR! State not outlined!n")
            }
        }

        self.connection?.begin(queue: .world())
    }

    func sendUDP(_ content material: Knowledge) {
        self.connection?.ship(content material: content material, completion: NWConnection.SendCompletion.contentProcessed(({ (NWError) in
            if (NWError == nil) {
                print("Knowledge was despatched to UDP")
            } else {
                print("ERROR! Error when information (Sort: Knowledge) sending. NWError: n (NWError!)")
            }
        })))
    }

    func sendUDP(_ content material: String) {
        let contentToSendUDP = content material.information(utilizing: String.Encoding.utf8)
        self.connection?.ship(content material: contentToSendUDP, completion: NWConnection.SendCompletion.contentProcessed(({ (NWError) in
            if (NWError == nil) {
                print("Knowledge was despatched to UDP")
            } else {
                print("ERROR! Error when information (Sort: Knowledge) sending. NWError: n (NWError!)")
            }
        })))
    }

    func receiveUDP() {
        print("Good day")
        self.connection?.receiveMessage { (information, context, isComplete, error) in
            if (isComplete) {
                print("Obtain is full")
                if (information != nil) {
                    let backToString = String(decoding: information!, as: UTF8.self)
                    print("Obtained message: (backToString)")
                } else {
                    print("Knowledge == nil")
                }
            }
            else{print("hmm")}
        }
    }
    

    
    @IBAction func connector(_ sender: UIButton) {print("making an attempt to attach")
        connectToUDP("239.255.255.250",37020)
        
    }
    @IBAction func receiverx(_ sender: UIButton) {
        print("receiving")
        receiveUDP()
    }
    
}

The swift app builds and runs, and appears to bind, but it surely by no means receives something.

I used to be questioning if the Community framework implements a buffer for the incoming information, during which case I ought to be capable to learn it off each time I like. If it would not, and the obtain operate solely listens for a brief period of time when invoked, then I may very well be lacking the incoming information.

Any recommendations?

[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments