如何在 iOS swift 中使用 UDP 套接字流式传输音频?
Posted
技术标签:
【中文标题】如何在 iOS swift 中使用 UDP 套接字流式传输音频?【英文标题】:How can I stream audio using UDP sockets in iOS swift? 【发布时间】:2018-09-08 13:29:13 【问题描述】:我对这个网络概念真的很陌生,但是我必须使用 UDP 套接字流式传输音频文件,并且在搜索了一周之后,我并没有真正得到任何有用的东西。我使用了 CocoaAsyncSocket,并尝试将字符串从发送方应用程序发送到接收方应用程序,但它没有收到任何内容。
import Foundation
import CocoaAsyncSocket
class OutSocket : NSObject, GCDAsyncUdpSocketDelegate
var hostIP : String = "255.255.255.255"
var port : UInt16 = 50008
var socket : GCDAsyncUdpSocket!
override init()
super.init()
setUpConnection()
func setUpConnection()
socket = GCDAsyncUdpSocket(delegate: self, delegateQueue: DispatchQueue.main)
do
try socket.connect(toHost: hostIP, onPort: port)
catch let err
print("Error Connecting, ", err)
func sendData(message : String)
guard let data = message.data(using: .utf8) else return
let str = String(data: data, encoding: .utf8)
print(str!)
socket.send(data, withTimeout: 1000, tag: 0)
func udpSocket(_ sock: GCDAsyncUdpSocket, didConnectToAddress address: Data)
print("didConnectToAddress")
func udpSocket(_ sock: GCDAsyncUdpSocket, didNotConnect error: Error?)
print("didNotConnect \(String(describing: error))")
func udpSocket(_ sock: GCDAsyncUdpSocket, didSendDataWithTag tag: Int)
print("didSendDataWithTag")
func udpSocket(_ sock: GCDAsyncUdpSocket, didNotSendDataWithTag tag: Int, dueToError error: Error?)
print("didNotSendDataWithTag")
print(error!)
import Foundation
import CocoaAsyncSocket
class InSocket: NSObject, GCDAsyncUdpSocketDelegate
var hostIP : String = "255.255.255.255"
var port : UInt16 = 50008
var socket : GCDAsyncUdpSocket!
override init()
super.init()
setUpConnection()
func setUpConnection()
socket = GCDAsyncUdpSocket(delegate: self, delegateQueue: DispatchQueue.main)
do
try socket.connect(toHost: hostIP, onPort: port)
try socket.bind(toPort: port)
try socket.enableBroadcast(true)
try socket.enableReusePort(true)
try socket.beginReceiving()
catch let err
print(err)
send(message: "Received")
func send(message:String)
guard let data = message.data(using: .utf8) else return
socket.send(data, withTimeout: 2, tag: 0)
在侦听器视图控制器中,我实现了 didReceive 委托方法,但它没有收到任何东西。任何人都可以至少帮助我处理字符串部分,以便我可以从发送者应用程序发送一个字符串并可以在接收者应用程序中接收吗?
【问题讨论】:
【参考方案1】:对于接收数据,您必须编写此方法 beginReceiving() 如果服务器向您发送信息,您将通过该方法从服务器获得响应。此方法启动接收过程,每当服务器发送任何内容时,您都会在 GCDAsyncUdpSocket 的 didReceiveData 委托中接收数据。
let socket = GCDAsyncUdpSocket(delegate: self, delegateQueue: DispatchQueue.main)
do
try socket.connect(toHost: hostIP, onPort: port)
try socket.beginReceiving()
catch let err
print("Error Connecting, ", err)
【讨论】:
以上是关于如何在 iOS swift 中使用 UDP 套接字流式传输音频?的主要内容,如果未能解决你的问题,请参考以下文章