{"id":1228,"date":"2020-11-19T15:02:08","date_gmt":"2020-11-19T07:02:08","guid":{"rendered":"http:\/\/123.57.164.21\/?p=1228"},"modified":"2021-03-05T22:09:13","modified_gmt":"2021-03-05T14:09:13","slug":"swift-%e4%bd%bf%e7%94%a8websocket%e5%8d%8f%e8%ae%ae%e5%92%8c%e6%9c%8d%e5%8a%a1%e5%99%a8%e9%80%9a%e4%bf%a1","status":"publish","type":"post","link":"https:\/\/92it.top\/?p=1228","title":{"rendered":"swift \u4f7f\u7528websocket\u534f\u8bae\u548c\u670d\u52a1\u5668\u901a\u4fe1"},"content":{"rendered":"\n<p>\u5173\u4e8ewebsocket\u534f\u8bae\u5c31\u4e0d\u591a\u505a\u4ecb\u7ecd\u4e86\uff0cwebsocket\u662f\u4e00\u79cd\u957f\u8fde\u63a5\u534f\u8bae\uff0c\u53ef\u4ee5\u5b9e\u73b0\u4ece\u5ba2\u6237\u7aef\u5230\u670d\u52a1\u5668\u7aef\u4e4b\u95f4\uff0c\u6d88\u606f\u7684\u5b9e\u65f6\u4f20\u9001\u3002<\/p>\n\n\n\n<h5 class=\"wp-block-heading\">1.\u9996\u5148\u662f\u670d\u52a1\u5668\u7aef\u7684\u4ee3\u7801\uff0c\u8fd9\u91cc\u7528nodejs\u505a\u4e3a\u670d\u52a1\u5668\u7aef\u4ee3\u7801\uff0cnodejs\uff0cwebsocket\u6709\u5f88\u591a\u6846\u67b6\uff0c\u6211\u4eec\u7528websocket ws\uff0c\u5e76\u4e14\u53d1\u5e03\u5230IBM Cloud\u7684 Cloud Foundry\u4e0a\u9762\u3002<\/h5>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\"><p>https:\/\/github.com\/websockets\/ws<\/p><p>https:\/\/www.npmjs.com\/package\/cfenv<\/p><p>https:\/\/www.kevinhoyt.com\/2015\/09\/02\/websockets-on-ibm-bluemix\/<\/p><\/blockquote>\n\n\n\n<ul><li>package.json<\/li><\/ul>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">{\n  \"name\": \"WebsocketServer\",\n  \"version\": \"1.0.0\",\n  \"description\": \"WebsocketServer\",\n  \"main\": \"server.js\",\n  \"scripts\": {\n    \"start\": \"node server.js\"\n  },\n  \"dependencies\": {\n    \"cfenv\": \"^1.2.3\",\n    \"express\": \"^4.16.4\",\n    \"http\": \"0.0.1-security\",\n    \"ws\": \"^7.4.0\"\n  }\n}\n<\/pre>\n\n\n\n<ul><li>server.js<\/li><\/ul>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">var cfenv = require( 'cfenv' );\nvar express = require( 'express' );\nvar http = require( 'http' );\nvar WebSocket = require( 'ws' );\n\n\/\/ Environment\nvar environment = cfenv.getAppEnv();\n\n\/\/ Web\nvar app = express();\n\nfunction noop() {};\n\nfunction heartbeat() {\n  console.log('get pong from client');\n  this.isAlive = true;\n};\n\nfunction sendPong() {\n  console.log('get ping from client');\n  this.pong(noop);\n};\n\n\/\/ Sockets\nvar server = http.createServer();\nvar wss = new WebSocket.Server( {\n  server: server\n} );\n\n wss.on('connection', function connection(ws, req) {\n   ws.isAlive = true;\n   \/\/ \u53ef\u4ee5\u901a\u8fc7req.headers \u53d6\u5f97Websocker\u4f20\u8fc7\u6765\u7684\u503c \u8fdb\u884c\u9a8c\u8bc1\uff0c \u9632\u6b62\u6ca1\u6709\u6743\u9650\u7684\u4eba\u8fde\u63a5\u670d\u52a1\u5668\u3002\n   if (req.headers.apikey != apiKey) {\n    ws.close();\n  }\n   \/\/ \u53ef\u4ee5\u628areq.headers\u7684\u67d0\u4e9b\u5c5e\u6027\u503c\u8d4b\u7ed9ws\uff08client\uff09\n   ws.username = req.headers.username\n   ws.uuid = req.headers.uuid\n   ws.role = req.headers.role\n \n   \/\/ \u5f53\u6536\u5230\u5ba2\u6237\u7aef\u7684Pong\u65f6\uff0c\u8bbe\u5b9a\u8be5connection isAlive\n   ws.on('pong', heartbeat);\n   \/\/ \u6536\u5230\u5ba2\u6237\u7aef\u7684Ping\u65f6\uff0c \u8fd4\u56dePong\n   ws.on('ping', sendPong);\n   ws.on('message', function incoming(data) {\n     wss.clients.forEach(function each(client) {\n\n       \/\/ \u4e0a\u9762ws\u8d4b\u7684\u503c\uff0c \u8fd9\u91cc\u53ef\u4ee5\u53d6\u5230\u4f7f\u7528\u3002\n       console.log( client.username );\n       console.log( client.uuid );\n       console.log( client.role );\n       if (client.readyState === WebSocket.OPEN) {\n         client.send(data);\n       }\n     });\n   });\n });\n\n\/\/ \u6bcf30\u79d2\u5f80\u5ba2\u6237\u7aef\u53d1\u9001Ping\uff0c\u7136\u540e\u7b49\u5f85\u5ba2\u6237\u7aefPong\u7684\u56de\u7b54\uff0c\u5982\u679c\u8d85\u65f6\uff0c\u6536\u4e0d\u5230\u6765\u81ea\u5ba2\u6237\u7aefPong\u7684\u56de\u7b54\uff0c\u5c31\u4e2d\u65ad\u8be5\u8fde\u63a5\uff0cws.terminate()\u3002\nconst interval = setInterval(function ping() {\n  wss.clients.forEach(function each(ws) {\n    if (ws.isAlive === false) return ws.terminate();\n    console.log('send ping to client');\n    ws.isAlive = false;\n    ws.ping(noop);\n  });\n}, 30000);\n\n wss.on('close', function close() {\n  clearInterval(interval);\n});\n\n\/\/ Start\nserver.on( 'request', app );\nserver.listen( environment.port, function() {\n  console.log( environment.url );\n} );<\/pre>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h5 class=\"wp-block-heading\">2.Swift\u7aef\u4ee3\u7801\uff0c\u4f5c\u4e3a\u5ba2\u6237\u7aef\uff0c\u8fde\u63a5websocket\u670d\u52a1\u5668\u3002Swift\u91c7\u7528Starscream \u8fde\u63a5webscoket\u670d\u52a1\u5668\uff0c\u53ef\u4ee5Pod\u5b89\u88c5Starscream\u3002<\/h5>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\"><p>https:\/\/github.com\/daltoniam\/Starscream<\/p><\/blockquote>\n\n\n\n<ul><li>Podfile\u6587\u4ef6<\/li><\/ul>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># Uncomment the next line to define a global platform for your project\n# platform :ios, '9.0'\n\ntarget 'WebSocketDemo' do\n  # Comment the next line if you don't want to use dynamic frameworks\n  use_frameworks!\n  pod 'Starscream'\n  # Pods for WebSocketDemo\n\nend\n<\/pre>\n\n\n\n<ul><li>SceneDelegate.swift<\/li><\/ul>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\/\/\n\/\/  SceneDelegate.swift\n\/\/  WebSocketDemo\n\/\/\n\/\/\n\nimport UIKit\nimport SwiftUI\nimport Starscream\n\nclass SceneDelegate: UIResponder, UIWindowSceneDelegate, WebSocketDelegate {\n\n    var isDisconnectedFromServer = false\n\n    func didReceive(event: WebSocketEvent, client: WebSocket) {\n        switch event {\n        case .connected(let headers):\n            print(\"websocket is connected: \\(headers)\")\n            isDisconnectedFromServer = false\n            NotificationCenter.default.post(name: .connected, object: nil, userInfo: nil)\n        case .disconnected(let reason, let code):\n            print(\"websocket is disconnected: \\(reason) with code: \\(code)\")\n            NotificationCenter.default.post(name: .disconnected, object: nil, userInfo: nil)\n        case .text(let string):\n            print(\"Received text: \\(string)\")\n            NotificationCenter.default.post(name: .text, object: string, userInfo: nil)\n        case .binary(let data):\n            print(\"Received data: \\(data.count)\")\n        case .ping(_):\n            break\n        case .pong(_):\n             \/\/ \u6536\u5230\u670d\u52a1\u5668\u8fd4\u56de\u7684Pong\u65f6\uff0c \u8bbe\u5b9a\u63a5\u7eed\u72b6\u6001\n            isDisconnectedFromServer = false\n            break\n        case .reconnectSuggested(_):\n            break\n        case .error(let error):\n            print(\"Received data: \\(String(describing: error))\")\n        case .viabilityChanged(_):\n            print(\"Received text: \")\n        case .cancelled:\n            print(\"Received text: )\")\n        }\n    }\n\n    var window: UIWindow?\n\n    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {\n        \/\/ Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.\n        \/\/ If using a storyboard, the `window` property will automatically be initialized and attached to the scene.\n        \/\/ This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).\n\n        \/\/ Create the SwiftUI view that provides the window contents.\n        let contentView = ContentView()\n\n        \/\/ Use a UIHostingController as window root view controller.\n        if let windowScene = scene as? UIWindowScene {\n            let window = UIWindow(windowScene: windowScene)\n            window.rootViewController = UIHostingController(rootView: contentView)\n            self.window = window\n            window.makeKeyAndVisible()\n        }\n        \/\/ request = URLRequest(url: URL(string: \"ws:\/\/localhost:1337\")!)\n\n        \/\/request = URLRequest(url: URL(string: \"https:\/\/WebSocketServer.au-syd.mybluemix.net\")!)\n        request = URLRequest(url: URL(string: \"ws:\/\/localhost:6001\")!)\n        request!.timeoutInterval = 5\n        \/\/ \u53ef\u4ee5\u7528request setValue \u5f80websocker Header\u91cc\u9762\u8bbe\u5b9a\u503c\u3002\n        request!.setValue(apiKey, forHTTPHeaderField: \"apikey\")\n        request!.setValue(\"login\", forHTTPHeaderField: \"action\")\n        request!.setValue(UIDevice.current.name, forHTTPHeaderField: \"username\")\n        request!.setValue(UIDevice.current.identifierForVendor!.uuidString, forHTTPHeaderField: \"uuid\")\n        socket = WebSocket(request: request!)\n        \/\/ \u662f\u5426\u81ea\u52a8\u5e94\u7b54\u670d\u52a1\u5668\u7684ping\uff0c\u5e94\u7b54\u56de\u670d\u52a1\u5668Pong\uff0c \u9ed8\u8ba4\u662ftrue\uff0c \u81ea\u52a8\u5e94\u7b54\u670d\u52a1\u5668\u7684Ping\uff0c \u8fd4\u56dePong\u3002\n        socket!.respondToPingWithPong = true\n\n        \/\/ \u4e5f\u53ef\u4ee5\u5199\u6210\n        \/\/ sceneDelegate = self\n        \/\/ socket!.delegate = sceneDelegate\n\n        socket!.delegate = self\n\n        \/\/ \u6bcf\u969420\u79d2\u5f80\u670d\u52a1\u5668\u7aef\u53d1\u4e00\u6b21Ping\uff0c \u770b\u662f\u5426\u80fd\u6536\u5230\u670d\u52a1\u5668\u8fd4\u56de\u7684Pong\n        Timer.scheduledTimer(withTimeInterval: 20, repeats: true, block: { [self] (refresher) in\n            if isDisconnectedFromServer == true {\n                print(\"\u548c\u670d\u52a1\u5668\u8fde\u63a5\u5df2\u7ecf\u4e2d\u65ad\")\n                \/\/ \u65ad\u5f00\u4ee5\u540e\u518d\u81ea\u52a8\u91cd\u65b0\u8fde\u63a5\u670d\u52a1\u5668\u3002\n                socket!.connect()\n                NotificationCenter.default.post(name: .disconnected, object: nil, userInfo: nil)\n            } else {\n                isDisconnectedFromServer = true\n                socket!.write(ping: Data())\n            }\n        })\n\n    }\n\n    func sceneDidDisconnect(_ scene: UIScene) {\n        \/\/ Called as the scene is being released by the system.\n        \/\/ This occurs shortly after the scene enters the background, or when its session is discarded.\n        \/\/ Release any resources associated with this scene that can be re-created the next time the scene connects.\n        \/\/ The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).\n    }\n\n    func sceneDidBecomeActive(_ scene: UIScene) {\n        \/\/ Called when the scene has moved from an inactive state to an active state.\n        \/\/ Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.\n    }\n\n    func sceneWillResignActive(_ scene: UIScene) {\n        \/\/ Called when the scene will move from an active state to an inactive state.\n        \/\/ This may occur due to temporary interruptions (ex. an incoming phone call).\n    }\n\n    func sceneWillEnterForeground(_ scene: UIScene) {\n        \/\/ Called as the scene transitions from the background to the foreground.\n        \/\/ Use this method to undo the changes made on entering the background.\n    }\n\n    func sceneDidEnterBackground(_ scene: UIScene) {\n        \/\/ Called as the scene transitions from the foreground to the background.\n        \/\/ Use this method to save data, release shared resources, and store enough scene-specific state information\n        \/\/ to restore the scene back to its current state.\n    }\n\n}\n\n<\/pre>\n\n\n\n<ul><li>ContentView.swift<\/li><\/ul>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\/\/\n\/\/  ContentView.swift\n\/\/  WebSocketDemo\n\/\/\n\/\/\n\nimport SwiftUI\n\nstruct ContentView: View {\n    @State var chatList: [String] = []\n    @State var name: String = \"\"\n    @State var chat: String = \"\"\n    @State var message: String = \"\"\n    @State var isConnectedFlag: Bool = false\n\n    var isConnected = NotificationCenter.default.publisher(for: .connected)\n    var isDisconnected = NotificationCenter.default.publisher(for: .disconnected)\n    var isText = NotificationCenter.default.publisher(for: .text)\n\n    var body: some View {\n        VStack {\n            \n            HStack {\n                TextField(\"\u30e1\u30c3\u30bb\u30fc\u30b8\", text: self.$chat).padding(.leading, 30)\n                Button(action: {\n                    socket?.write(string: self.chat)\n                }) {\n                    Text(\"\u9001\u4fe1\")\n                }.padding(.trailing, 30).disabled(self.chat != \"\" ? false : true)\n            }.padding(.top, 50)\n\n            Spacer()\n\n            ScrollView(showsIndicators: false) {\n                Text(\"\").frame(width: UIScreen.main.bounds.width - 50, height: 1)\n                VStack(spacing: 10) {\n                    ForEach(self.chatList, id: \\.self) { message in\n                        Text(message)\n                    }\n                }\n            }.frame(width: UIScreen.main.bounds.width - 50, height: UIScreen.main.bounds.height - 180).background(Color(red: 227 \/ 255, green: 227 \/ 255, blue: 227 \/ 255, opacity: 1))\n\n            Spacer()\n            \n            HStack {\n                Button(action: {\n                    if !self.isConnectedFlag {\n                        socket?.connect()\n                    } else {\n                        socket?.disconnect()\n                        self.isConnectedFlag = false\n                        self.message = \"\"\n                    }\n                }) {\n                    if !self.isConnectedFlag {\n                        Text(\"\u30b5\u30fc\u30d0\u3092\u63a5\u7d9a\")\n                    } else {\n                        Text(\"\u63a5\u7d9a\u4e2d\u65ad\")\n                    }\n\n                }.padding(.leading, 30)\n                Spacer()\n                Text(self.message).padding(.trailing, 30)\n            }.padding(.bottom, 50)\n           \n\n        }.frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height, alignment: .center).onReceive(isConnected) { _ in\n            self.message = \"\u63a5\u7d9a\u6210\u529f\"\n            self.isConnectedFlag = true\n        }.onReceive(isText) { message in\n            self.chatList.append(message.object as! String)\n        }.onReceive(isDisconnected) { _ in\n            self.message = \"\"\n            self.isConnectedFlag = false\n        }\n\n    }\n}\n\nstruct ContentView_Previews: PreviewProvider {\n    static var previews: some View {\n        ContentView()\n    }\n}\n<\/pre>\n\n\n\n<ul><li>Common.swift<\/li><\/ul>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\/\/\n\/\/  Common.swift\n\/\/  WebSocketDemo\n\/\/\n\/\/\n\nimport Foundation\nimport Starscream\n\nvar socket: WebSocket?\nvar request: URLRequest?\n\nextension Notification.Name {\n\n    static var connected: Notification.Name {\n        Notification.Name(\"connected\")\n    }\n    \n    static var disconnected: Notification.Name {\n        Notification.Name(\"disconnected\")\n    }\n    \n    static var text: Notification.Name {\n        Notification.Name(\"text\")\n    }\n}\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>\u5173\u4e8ewebsocket\u534f\u8bae\u5c31\u4e0d\u591a\u505a\u4ecb\u7ecd\u4e86\uff0cwebsocket\u662f\u4e00\u79cd\u957f\u8fde\u63a5\u534f\u8bae\uff0c\u53ef\u4ee5\u5b9e\u73b0\u4ece\u5ba2\u6237\u7aef\u5230\u670d\u52a1\u5668\u7aef\u4e4b\u95f4\uff0c [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[6,8],"tags":[],"_links":{"self":[{"href":"https:\/\/92it.top\/index.php?rest_route=\/wp\/v2\/posts\/1228"}],"collection":[{"href":"https:\/\/92it.top\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/92it.top\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/92it.top\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/92it.top\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=1228"}],"version-history":[{"count":11,"href":"https:\/\/92it.top\/index.php?rest_route=\/wp\/v2\/posts\/1228\/revisions"}],"predecessor-version":[{"id":2003,"href":"https:\/\/92it.top\/index.php?rest_route=\/wp\/v2\/posts\/1228\/revisions\/2003"}],"wp:attachment":[{"href":"https:\/\/92it.top\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=1228"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/92it.top\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=1228"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/92it.top\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=1228"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}