title: Connecting To A Socket and Listening In Swift
body: <p>I am trying to implement an iOS swift tool for collecting information from network devices. Knowing the multicast address and port, I can bind and receive the information that's being transmitted from the network hardware, such as serial info and manufacturer etc.</p>
  <p>I have a working prototype of the tool in python, which opens a socket on a multicast address (and port) and them prints what it receives.</p>
  <p>Which looks like this:</p>
  <pre><code>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 groups
      sock.bind(('', MCAST_PORT))
  else:
      # on this port, listen ONLY to MCAST_GRP
      sock.bind((MCAST_GRP, MCAST_PORT))
  mreq = struct.pack(&quot;4sl&quot;, socket.inet_aton(MCAST_GRP), socket.INADDR_ANY)
  
  sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
  
  
  
  while True:
    data, (ip, port) = sock.recvfrom(4096)
    print (ip,port)
    print(data)
  </code></pre>
  <p>My attempt at implementing this in swift looks like this (made up of snippets I've found online):</p>
  <pre><code>import UIKit
  import Network
  
  class ViewController: UIViewController {
  
      var connection: NWConnection?
      var hostUDP: NWEndpoint.Host = &quot;239.255.255.250&quot;
      var portUDP: NWEndpoint.Port = 37020
  
      override func viewDidLoad() {
          super.viewDidLoad()
  
          // Hack to wait until everything is set up
          var x = 0
          while(x&lt;1000000000) {
              x+=1
          }
          connectToUDP(hostUDP,portUDP)
      }
  
      func connectToUDP(_ hostUDP: NWEndpoint.Host, _ portUDP: NWEndpoint.Port) {
          // Transmited message:
          let messageToUDP = &quot;Test message&quot;
  
          self.connection = NWConnection(host: hostUDP, port: portUDP, using: .udp)
  
          self.connection?.stateUpdateHandler = { (newState) in
              print(&quot;This is stateUpdateHandler:&quot;)
              switch (newState) {
                  case .ready:
                      print(&quot;State: Ready\n&quot;)
                  case .setup:
                      print(&quot;State: Setup\n&quot;)
                  case .cancelled:
                      print(&quot;State: Cancelled\n&quot;)
                  case .preparing:
                      print(&quot;State: Preparing\n&quot;)
                  default:
                      print(&quot;ERROR! State not defined!\n&quot;)
              }
          }
  
          self.connection?.start(queue: .global())
      }
  
      func sendUDP(_ content: Data) {
          self.connection?.send(content: content, completion: NWConnection.SendCompletion.contentProcessed(({ (NWError) in
              if (NWError == nil) {
                  print(&quot;Data was sent to UDP&quot;)
              } else {
                  print(&quot;ERROR! Error when data (Type: Data) sending. NWError: \n \(NWError!)&quot;)
              }
          })))
      }
  
      func sendUDP(_ content: String) {
          let contentToSendUDP = content.data(using: String.Encoding.utf8)
          self.connection?.send(content: contentToSendUDP, completion: NWConnection.SendCompletion.contentProcessed(({ (NWError) in
              if (NWError == nil) {
                  print(&quot;Data was sent to UDP&quot;)
              } else {
                  print(&quot;ERROR! Error when data (Type: Data) sending. NWError: \n \(NWError!)&quot;)
              }
          })))
      }
  
      func receiveUDP() {
          print(&quot;Hello&quot;)
          self.connection?.receiveMessage { (data, context, isComplete, error) in
              if (isComplete) {
                  print(&quot;Receive is complete&quot;)
                  if (data != nil) {
                      let backToString = String(decoding: data!, as: UTF8.self)
                      print(&quot;Received message: \(backToString)&quot;)
                  } else {
                      print(&quot;Data == nil&quot;)
                  }
              }
              else{print(&quot;hmm&quot;)}
          }
      }
      
  
      
      @IBAction func connector(_ sender: UIButton) {print(&quot;attempting to connect&quot;)
          connectToUDP(&quot;239.255.255.250&quot;,37020)
          
      }
      @IBAction func receiverx(_ sender: UIButton) {
          print(&quot;receiving&quot;)
          receiveUDP()
      }
      
  }
  </code></pre>
  <p>The swift app builds and runs, and seems to bind, but it never receives anything.</p>
  <p>I was wondering if the Network framework implements a buffer for the incoming data, in which case I should be able to read it off whenever I like. If it doesn't, and the receive function only listens for a short amount of time when invoked, then I could be missing the incoming data.</p>
  <p>Any suggestions?</p>