ios 如何在 iPhone 上实现 UDP 客户端并在 Swift 中发送数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28295486/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 04:38:52  来源:igfitidea点击:

How to implement UDP client and send data in Swift on iPhone?

iossocketsswiftudp

提问by Martin

I want to develop UDP client and send data in Swift.

我想开发UDP客户端并在Swift中发送数据。

I have reference the following link:

我参考了以下链接:

Swift: Receive UDP with GCDAsyncUdpSocket

Swift:使用 GCDAsyncUdpSocket 接收 UDP

Retrieving a string from a UDP server message

从 UDP 服务器消息中检索字符串

Swift UDP Connection

快速 UDP 连接

But I could not find a good way to implement UDPin Swift.

但是我找不到UDPSwift.

Can someone teach me How to implement UDP client and send data in Swift on iPhone?

有人可以教我如何在 iPhone 上用 Swift 实现 UDP 客户端和发送数据吗?

回答by AbdulMomen ?????????

for me, I used this, and its usage:

对我来说,我使用了this及其用法:

broadcastConnection = UDPBroadcastConnection(port: 35602) { [unowned self] (response: (ipAddress: String, port: Int, response: [UInt8])) -> Void in
    print("Received from \(response.ipAddress):\(response.port):\n\n\(response.response)")
}

回答by ingconti

very nice sample! My two cents.. fixed for swift 4.2. / Xcode 10, (I love using 20 lines instead of a bunch of other files.. and Pods.. ). Added some more returned results.

非常好的样品!我的两美分.. 固定为 swift 4.2。/ Xcode 10,(我喜欢使用 20 行而不是一堆其他文件……和 Pods……)。添加了更多返回的结果。

import Foundation

func udpSend(textToSend: String, address: in_addr, port: CUnsignedShort) {


func htons(value: CUnsignedShort) -> CUnsignedShort {
    return (value << 8) + (value >> 8);
}

let fd = socket(AF_INET, SOCK_DGRAM, 0) // DGRAM makes it UDP

let addr = sockaddr_in(
    sin_len:    __uint8_t(MemoryLayout<sockaddr_in>.size),
    sin_family: sa_family_t(AF_INET),
    sin_port:   htons(value: port),
    sin_addr:   address,
    sin_zero:   ( 0, 0, 0, 0, 0, 0, 0, 0 )
)

let sent = textToSend.withCString { cstr -> Int in

    var localCopy = addr

    let sent = withUnsafePointer(to: &localCopy) { pointer -> Int in
        let memory = UnsafeRawPointer(pointer).bindMemory(to: sockaddr.self, capacity: 1)
        let sent = sendto(fd, cstr, strlen(cstr), 0, memory, socklen_t(addr.sin_len))
        return sent
    }

    return sent
}

close(fd)

}

}

回答by hnh

This looks like a dupe to Swift UDP Connection.

这看起来像是对Swift UDP Connection的欺骗。

Refactoring the example a little bit:

稍微重构一下示例:

let INADDR_ANY = in_addr(s_addr: 0)

udpSend("Hello World!", address: INADDR_ANY, port: 1337)

func udpSend(textToSend: String, address: in_addr, port: CUnsignedShort) {
  func htons(value: CUnsignedShort) -> CUnsignedShort {
    return (value << 8) + (value >> 8);
  }

  let fd = socket(AF_INET, SOCK_DGRAM, 0) // DGRAM makes it UDP

  var addr = sockaddr_in(
    sin_len:    __uint8_t(sizeof(sockaddr_in)),
    sin_family: sa_family_t(AF_INET),
    sin_port:   htons(port),
    sin_addr:   address,
    sin_zero:   ( 0, 0, 0, 0, 0, 0, 0, 0 )
  )

  textToSend.withCString { cstr -> Void in
    withUnsafePointer(&addr) { ptr -> Void in
      let addrptr = UnsafePointer<sockaddr>(ptr)
      sendto(fd, cstr, strlen(cstr), 0, addrptr, socklen_t(addr.sin_len))
    }
  }

  close(fd)
}

If you have the target IP as a string, use inet_pton() to convert it to an in_addr. Like so:

如果您将目标 IP 作为字符串,请使用 inet_pton() 将其转换为 in_addr。像这样:

var addr = in_addr()
inet_pton(AF_INET, "192.168.0.1", &buf)

Feel free to steal code from over here: SwiftSockets

随意从这里窃取代码:SwiftSockets

Oh, and if you plan to do any serious network programming, grab this book: Unix Network Programming

哦,如果您打算进行任何严肃的网络编程,请阅读本书:Unix 网络编程

回答by Ash

After pretty extensive research coming up with only basic pointers towards GCD's AsyncSocket, and being a pure Swift trained iOS programmer, I looked for something with native Swift socket support.

经过相当广泛的研究,只找到了 GCD 的 AsyncSocket 的基本指针,并且作为一名纯 Swift 训练有素的 iOS 程序员,我寻找具有原生 Swift 套接字支持的东西。

Thankfully, I found a much simpler alternative to using Async, called SwiftSocket.

谢天谢地,我找到了一个更简单的异步替代方法,称为 SwiftSocket。

The github (https://github.com/xyyc/SwiftSocket) has examples for most sockets, and is ready to use by copying just a few files into a project.

github ( https://github.com/xyyc/SwiftSocket) 提供了大多数套接字的示例,只需将几个文件复制到项目中即可使用。

For swift-only devs, I feel its underutilized and will quickly replace Async for non-objective-c apps. Then again I'm pretty new to this stuff so I may be way off :D

对于只使用 swift 的开发人员,我觉得它没有得到充分利用,并将很快取代 Async 用于非目标 C 应用程序。再说一次,我对这些东西很陌生,所以我可能会离开:D