对于这个网络概念我真的很陌生,但是我必须使用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控制器中,我实现了didReceive委托方法,但未接收任何东西。有人可以至少在字符串部分帮助我,以便我可以从发送方应用发送字符串并可以在接收方应用中接收吗?
答案 0 :(得分:0)
要接收数据,您必须编写此方法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)
}