如何接收UDP组播和单播与网络框架的iOS

2022-01-28 02:54:37 标签 iosudpmulticastunicast

我一直在开发智能房子的应用程序,需要UDP通信的单播和多播在iOS与Swift使用CocoaAsyncSocket。

我想使用网络框架而不是CocoaAsyncSocket。

我在“224。0。23。0”上做了一个在3610端口同时使用Unicast和Multicast接收UDP的试验程序。

用这个程序,我有一个问题,以接收组播和单播。

该程序可以处理接收组播,但不能处理单播。

当我在init()中注释掉“receiveMulticast()”时,这个程序可以处理接收单播。

我需要处理接收组播和单播在3610端口。

有什么建议吗?

=======================================

import Foundation
import Network
class Controller: ObservableObject {
  @Published var rxContents = String()
  @Published var rxFrom = String()
  
  init() {
    receiveMulticast()
    receiveUnicast()
  }
  
  func receiveUnicast() {
    guard let listener = try? NWListener(using: .udp, on: 3610)
    else { fatalError() }
    listener.newConnectionHandler = { (newConnection) in
      print("connection OK")
      newConnection.start(queue: .main)
      self.receive(on: newConnection)
    }
    listener.stateUpdateHandler = { (newState) in
      print("listener entered state \(String(describing: newState))")
    }
    listener.start(queue: .main)
  }
  func receiveMulticast() {
    guard let multicast = try? NWMulticastGroup(for: [ .hostPort(host: "224.0.23.0", port: 3610) ], disableUnicast: false)
    else { fatalError() }
    let group = NWConnectionGroup(with: multicast, using: .udp)
    group.setReceiveHandler(maximumMessageSize: 16384, rejectOversizedMessages: true) { (message, content, isComplete) in
      print("Received message from \(String(describing: message.remoteEndpoint))")
      if let content = content, let message = String(data: content, encoding: .utf8) {
        print("Received Message: \(message)")
      }
    }
    group.stateUpdateHandler = { (newState) in
      print("Group entered state \(String(describing: newState))")
    }
    group.start(queue: .main)
  }
  
  private func receive(on connection: NWConnection) {
    connection.receiveMessage { (data: Data?, contentContext: NWConnection.ContentContext?, aBool: Bool, error: NWError?) in
      self.rxFrom = String(describing: connection.endpoint)
      print("Received message from \(self.rxFrom))")
      print(data ?? "data is null")
      if let data = data{
        self.rxContents = String(format: "%@", data as CVarArg)
        print("Received Message(unicast): \(self.rxContents)")
      }
      if let error = error {
        print(error)
      } else {
        self.receive(on: connection)
      }
    }
  }
}
阅读全文

▼ 版权说明

相关文章也很精彩
推荐内容
更多标签
相关热门
全站排行
随便看看

错说 cuoshuo.com —— 程序员的报错记录

部分内容根据CC版权协议转载;网站内容仅供参考,生产环境使用务必查阅官方文档

辽ICP备19011660号-5

×

扫码关注公众号:职场神器
发送: 1
获取永久解锁本站全部文章的验证码