本文介绍了快速 UDP 连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Swift 新手,对 UDP 连接有一些疑问.

I am new to Swift and have some questions about UDP connections.

谁能提供一个链接或一些简短的代码行,展示我如何将 Swift 客户端连接到 Java 服务器?

Could someone provide a link or some short lines of code showing how I can connect a Swift client to a Java server?

推荐答案

您可以只使用Darwin"模块中的相关 C 函数.有点棘手的部分是从 sockaddr_xyz 结构到通用 sockaddr 的转换(也许有人有比我更好的解决方案......).否则就很简单了.

You can just use the relevant C functions, from the 'Darwin' module. The part which is a bit tricky is the casting from sockaddr_xyz structs to the generic sockaddr (maybe someone has a better solution than mine ...). Otherwise it is pretty straight forward.

针对 Swift 0.2 aka Xcode 6.3.1 进行了更新(strlen() 必须转换为 Int).

Updated for Swift 0.2 aka Xcode 6.3.1 (strlen() must be converted to Int).

示例:

let textToSend = "Hello World!"

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

let INADDR_ANY = in_addr(s_addr: 0)

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(1337),
  sin_addr:   INADDR_ANY,
  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, Int(strlen(cstr)), 0,
           addrptr, socklen_t(addr.sin_len))
  }
}

这篇关于快速 UDP 连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 21:18