我正在尝试在我的应用程序中实现swift套接字。我是套接字编程的新手。我用过
https://github.com/swiftsocket/SwiftSocket
用于套接字连接。我已经为服务器连接创建了NSObject类。
我希望服务器通过我的整个应用程序连接,但是当我移到另一个ViewController时,服务器已断开连接。
class SocketGLobal : NSObject
{
func Connect()
{
let client = TCPClient(address: "www.apple.com", port: 80)
switch client.connect(timeout: 1) {
case .success:
switch client.send(string: "GET / HTTP/1.0\n\n" ) {
case .success:
guard let data = client.read(1024*10) else { return }
if let response = String(bytes: data, encoding: .utf8) {
print(response)
}
case .failure(let error):
print(error)
}
case .failure(let error):
print(error)
}
}
}
答案 0 :(得分:0)
我遇到了同样的问题。因此,我创建了自定义ViewController并将 GCDAsyncUdpSocket 用于套接字连接。在您的pod文件中添加pod 'CocoaAsyncSocket'
以使用 GCDAsyncUdpSocket 。这是自定义ViewController的代码段。
import CocoaAsyncSocket
class CustomViewController: UIViewController, GCDAsyncUdpSocketDelegate {
//MARK: VARIABLE DECLARATION **********
var _udpSocket: GCDAsyncUdpSocket?
var udpSocket: GCDAsyncUdpSocket? {
get {
if _udpSocket == nil {
let port = 80
let sock = GCDAsyncUdpSocket(delegate: self, delegateQueue: DispatchQueue.main)
do {
sock.setIPv6Enabled(false)
// sock?.setIPv4Enabled(true)
// sock?.setPreferIPv4()
try sock.enableBroadcast(true)
try sock.bind(toPort: UInt16(port))
try sock.beginReceiving()
} catch let err as NSError {
print(">>> Error while initializing socket: \(err.localizedDescription)")
sock.close()
return nil
}
_udpSocket = sock
}
return _udpSocket
}
set {
_udpSocket?.close()
_udpSocket = newValue
}
}
//MARK: UDP SERVICES *********
//Start UDP Receiver
func startUDPService(){
guard udpSocket != nil else {
return
}
}
//Stop UDP Receiver
func closeUDPService(){
if udpSocket != nil {
udpSocket?.close()
udpSocket = nil
}
}
//MARK: HANDLING OF RECEIVED DATA **********
func udpSocket(_ sock: GCDAsyncUdpSocket, didReceive data: Data, fromAddress address: Data, withFilterContext filterContext: Any?) {
var hostPtr : NSString? = nil
GCDAsyncUdpSocket.getHost(&hostPtr, port: &send_port, fromAddress: address)
var receivedText = ""
if let stringData = String(data: data as Data, encoding: String.Encoding.utf8) {
receivedText = stringData
}
print("Data received: \(String(describing: hostPtr)), \(receivedText)")
}
}
在每个ViewController实现中,如下所示:
import UIKit
class YourViewController: CustomViewController {
//MARK: LIFE CYCLE METHODS **********
override func viewWillAppear(_ animated: Bool) {
//MARK: START UDP SERVICE
self.startUDPService()
}
override func viewWillDisappear(_ animated: Bool) {
//MARK: STOP UDP SERVICE
self.closeUDPService()
}
}
我希望这会对您有所帮助。