gpt4 book ai didi

swift - 如何在 iOS swift 中使用 UDP 套接字流式传输音频?

转载 作者:搜寻专家 更新时间:2023-11-01 05:32:50 29 4
gpt4 key购买 nike

我对这个网络概念真的很陌生,但我必须使用 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)
}

在 Listener View Controller 中,我已经实现了 didReceive 委托(delegate)方法,但它没有接收到任何东西。任何人都可以至少在字符串部分帮助我,以便我可以从发件人应用程序发送一个字符串并可以在接收者应用程序中接收吗?

最佳答案

对于接收数据,您必须编写此方法 beginReceiving() 如果服务器向您发送内容,您将通过该方法从服务器获得响应。此方法启动接收过程,每当服务器发送任何东西时,您将在 GCDAsyncUdpSocket 的 didReceiveData 委托(delegate)中接收数据。

  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)
}

关于swift - 如何在 iOS swift 中使用 UDP 套接字流式传输音频?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52235827/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com