UDP连接Swift问题
发布时间:2022-08-09 23:45:56 319
相关标签: # swift# 服务器# 数据# 服务器
我试图在Swift中使用UDP连接到外部硬件,但当我尝试发送数据时,它只将数据发送到IP255.255.255.255
192.168.4.1.
使用Wireshark检查数据包,它仅在IP为255.255.255.255
这是行不通的,因为服务器没有收到。
服务器工作正常,因为我将其与C代码一起使用,没有任何问题。
import Foundation
import Network
import Combine
class UDPListener: ObservableObject {
var listener: NWListener?
var connection: NWConnection?
var queue = DispatchQueue.global(qos: .userInitiated)
/// New data will be place in this variable to be received by observers
@Published private(set) public var messageReceived: Data?
/// When there is an active listening NWConnection this will be `true`
@Published private(set) public var isReady: Bool = false
/// Default value `true`, this will become false if the UDPListener ceases listening for any reason
@Published public var listening: Bool = true
/// A convenience init using Int instead of NWEndpoint.Port
convenience init(on port: Int) {
self.init(on: NWEndpoint.Port(integerLiteral: NWEndpoint.Port.IntegerLiteralType(port)))
}
/// Use this init or the one that takes an Int to start the listener
init(on port: NWEndpoint.Port) {
let params = NWParameters.udp
params.allowFastOpen = true
params.allowLocalEndpointReuse = true
self.listener = try? NWListener(using: params, on: port)
self.listener?.stateUpdateHandler = { update in
switch update {
case .ready:
self.isReady = true
print("Listener connected to port \(port)")
case .failed, .cancelled:
// Announce we are no longer able to listen
self.listening = false
self.isReady = false
print("Listener disconnected from port \(port)")
default:
print("Listener connecting to port \(port)...")
}
}
self.listener?.newConnectionHandler = { connection in
print("Listener receiving new message")
self.createConnection(connection: connection)
}
self.listener?.start(queue: self.queue)
}
func createConnection(connection: NWConnection) {
self.connection = connection
self.connection?.stateUpdateHandler = { (newState) in
switch (newState) {
case .ready:
print("Listener ready to receive message - \(connection)")
self.receive()
case .cancelled, .failed:
print("Listener failed to receive message - \(connection)")
// Cancel the listener, something went wrong
self.listener?.cancel()
// Announce we are no longer able to listen
self.listening = false
default:
print("Listener waiting to receive message - \(connection)")
}
}
self.connection?.start(queue: .global())
}
func receive() {
self.connection?.receiveMessage { data, context, isComplete, error in
if let unwrappedError = error {
print("Error: NWError received in \(#function) - \(unwrappedError)")
return
}
guard isComplete, let data = data else {
print("Error: Received nil Data with context - \(String(describing: context))")
return
}
self.messageReceived = data
if self.listening {
self.receive()
}
}
}
func cancel() {
self.listening = false
self.connection?.cancel()
}
}
和SwiftUI:
//
// ContentView.swift
// Shared
//
// Created by Sebas Bejenaru on 18/7/22.
//
import SwiftUI
import Network
struct ContentView: View {
@State var connection: NWConnection?
var host: NWEndpoint.Host = "255.255.255.255"
var port: NWEndpoint.Port = 8080
var body: some View {
VStack {
Spacer()
Button("Setup") {
NSLog("Connect pressed")
setup()
}
Spacer()
Button("Connect") {
NSLog("Connect pressed")
connect()
}
Spacer()
Button("Send") {
NSLog("Send pressed")
send("S".data(using: .utf8)!)
}
Spacer()
}.padding()
}
func setup() {
let listener = UDPListener(on: 8080)
let udpListener = NWParameters.udp
udpListener.allowLocalEndpointReuse = true
let connection = NWConnection(host: host, port: port, using: udpListener)
listener.createConnection(connection: connection)
listener.connection?.send(content: ("S".data(using: .utf8)!), completion: .contentProcessed({ sendError in
if let error = sendError {
NSLog("Unable to process and send the data: \(error)")
} else {
NSLog("Data has been sent")
listener.connection!.receiveMessage { (data, context, isComplete, error) in
guard let myData = data else { return }
print("received data")
print(myData)
}
}
}))
listener.receive()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报