如何解决没有握手的iOS网络套接字
我想在iOS上建立一个简单的本地Socket通信。在研究了其他库之后,我发现自去年以来,Swift原生提供的websocket库运行良好,但是带有一个我想禁用的讨厌的握手(否则,我将不得不调整服务器响应等)。我的代码如下:
let webSocketDelegate = WebSocket()
let session = URLSession(configuration: .default,delegate: webSocketDelegate,delegateQueue: OperationQueue())
let url = URL(string: "ws://192.168.43.1:6000")!
let webSocketTask = session.webSocketTask(with: url)
func send() {
dispatchQueue.global().asyncAfter(deadline: .Now() + 1) {
send()
webSocketTask.send(.string("New Message")) { error in
if let error = error {
print("Error when sending a message \(error)")
}
}
}
}
webSocketTask.receive { result in
switch result {
case .success(let message):
switch message {
case .data(let data):
print("Data received \(data)")
case .string(let text):
print("Text received \(text)")
}
case .failure(let error):
print("Error when receiving \(error)")
}
}
webSocketTask.resume()
我用Google搜索并找到了nw_ws_options_set_skip_handshake,但找不到如何使用它的示例。有什么想法吗?
解决方法
正如@SteffenUllrich所建议的,我对TCP套接字通信进行了更多研究,并找到了一种简单的通信方式。这是我的解决方案,希望对您有所帮助。
let queue = DispatchQueue(label: "TCP Client Queue")
let connection = NWConnection(to: NWEndpoint.hostPort(host: "192.168.99.1",port: 7000),using: NWParameters.init(tls: nil))
func connect() {
connection.stateUpdateHandler = { (newState) in
switch (newState) {
case .ready:
print("Socket: ready")
sendString(text: "Hello server!")
receiveMsg()
default: print("Socket: \(newState)")
}
}
connection.start(queue: queue)
}
func receiveMsg() {
connection.receive(minimumIncompleteLength: 1,maximumLength: 1000,completion: { (data,context,isComplete,error) in
if((data) != nil){
let text:String = String(decoding: data!,as: UTF8.self)
//send string to handler function,trim linebreak for single line commands
handleMsg(msg: text.trimmingCharacters(in: .newlines))
}
else{receiveMsg()//go back to receiving}
})
}
func receiveFile() {
print("Receiving file...")
//fileSize was sent before submission
connection.receive(minimumIncompleteLength: Int(fileSize),maximumLength: Int(fileSize)+1000,error) in
saveFile(data: data!)//save data to file
})
}
func sendString(text:String) {
let data:Data? = "\(text)\n".data(using: .utf8)//add linebreak to single line string,otherwise it does not release transmission
connection.send(content: data,completion: NWConnection.SendCompletion.contentProcessed(({ (NWError) in
if (NWError == nil) {
print("Data was sent to TCP destination ")
} else {
print("ERROR! Error when data (Type: Data) sending. NWError: \n \(NWError!)")
}
})))
}
您只需要调用connect()即可开始连接,使用sendString()发送一些文本。接收应持续运行。我没有共享命令处理程序,但是它在常规命令上重新运行receiveMsg(),并在服务器启动文件传输时重新运行receiveFile()(初始化文件还包含在文件中设置预期字节大小所需的fileSize)。 receive()函数!)。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。