gpt4 book ai didi

ios - Swift:使用 GCDAsyncUdpSocket 接收 UDP

转载 作者:IT王子 更新时间:2023-10-29 05:16:00 29 4
gpt4 key购买 nike

背景:

我希望能够在我的 iOS 应用和服务器之间发送和接收 UDP 数据包。服务器将每条传入消息回显给客户端应用程序。 服务器已经过测试并确认可以正常工作。我有一个 StartViewController,它启动了两个实现 GCDAsyncUdpSocketDelegate 的类,一个用于发送,一个用于接收。 “发送套接字”正在工作,服务器接收消息。

问题:

应用程序永远不会在发送消息后取回传入的消息。监听套接字设置可能有问题,因为 didReceiveData 从未被调用过。

我做错了吗?

开始:

class StartViewController: UIViewController {

var inSocket : InSocket!
var outSocket : OutSocket!

override func viewDidLoad() {
super.viewDidLoad()
inSocket = InSocket()
outSocket = OutSocket()
}

@IBAction func goButton(sender: UIButton) {
outSocket.send("This is a message!")
}
}

接收:

class InSocket: NSObject, GCDAsyncUdpSocketDelegate {

let IP = "255.255.255.255"
let PORT:UInt16 = 5556
var socket:GCDAsyncUdpSocket!

override init(){
super.init()
setupConnection()
}

func setupConnection(){
var error : NSError?
socket = GCDAsyncUdpSocket(delegate: self, delegateQueue: dispatch_get_main_queue())
socket.bindToPort(PORT, error: &error)
socket.enableBroadcast(true, error: &error)
socket.joinMulticastGroup(IP, error: &error)
socket.beginReceiving(&error)
}

func udpSocket(sock: GCDAsyncUdpSocket!, didReceiveData data: NSData!, fromAddress address: NSData!, withFilterContext filterContext: AnyObject!) {
println("incoming message: \(data)");
}
}

发送:

class OutSocket: NSObject, GCDAsyncUdpSocketDelegate {

let IP = "90.112.76.180"
let PORT:UInt16 = 5556
var socket:GCDAsyncUdpSocket!

override init(){
super.init()
setupConnection()
}

func setupConnection(){
var error : NSError?
socket = GCDAsyncUdpSocket(delegate: self, delegateQueue: dispatch_get_main_queue())
socket.connectToHost(IP, onPort: PORT, error: &error)
}

func send(message:String){
let data = message.dataUsingEncoding(NSUTF8StringEncoding)
socket.sendData(data, withTimeout: 2, tag: 0)
}

func udpSocket(sock: GCDAsyncUdpSocket!, didConnectToAddress address: NSData!) {
println("didConnectToAddress");
}

func udpSocket(sock: GCDAsyncUdpSocket!, didNotConnect error: NSError!) {
println("didNotConnect \(error)")
}

func udpSocket(sock: GCDAsyncUdpSocket!, didSendDataWithTag tag: Int) {
println("didSendDataWithTag")
}

func udpSocket(sock: GCDAsyncUdpSocket!, didNotSendDataWithTag tag: Int, dueToError error: NSError!) {
println("didNotSendDataWithTag")
}
}

编辑:添加了被遗忘的代码行。

最佳答案

我终于让它与这个套接字设置一起工作:

func setupConnection(){
var error : NSError?
socket = GCDAsyncUdpSocket(delegate: self, delegateQueue: dispatch_get_main_queue())
socket.bindToPort(PORT, error: &error)
socket.connectToHost(SERVER_IP, onPort: PORT, error: &error)
socket.beginReceiving(&error)
send("ping")
}

func send(message:String){
let data = message.dataUsingEncoding(NSUTF8StringEncoding)
socket.sendData(data, withTimeout: 2, tag: 0)
}

关于ios - Swift:使用 GCDAsyncUdpSocket 接收 UDP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26790129/

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