├── .gitignore ├── README.md ├── WSServer ├── .buildzz │ ├── Package.resolved │ ├── Package.swift │ └── Sources │ │ └── WSServer │ │ └── dummy.swift ├── Package.swift └── Sources │ └── WSServer │ └── main.swift ├── WebSockets.xcodeproj ├── project.pbxproj └── project.xcworkspace │ ├── contents.xcworkspacedata │ └── xcshareddata │ ├── IDEWorkspaceChecks.plist │ └── swiftpm │ └── Package.resolved ├── WebSockets ├── AppDelegate.swift ├── Assets.xcassets │ ├── AppIcon.appiconset │ │ └── Contents.json │ └── Contents.json ├── Base.lproj │ └── LaunchScreen.storyboard ├── ContentView.swift ├── Info.plist ├── Preview Content │ └── Preview Assets.xcassets │ │ └── Contents.json ├── SceneDelegate.swift └── WebSocketConnection.swift └── images └── websocket.jpg /.gitignore: -------------------------------------------------------------------------------- 1 | # Xcode 2 | # 3 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore 4 | 5 | .DS_Store 6 | 7 | ## Build generated 8 | build/ 9 | DerivedData/ 10 | 11 | ## Various settings 12 | *.pbxuser 13 | !default.pbxuser 14 | *.mode1v3 15 | !default.mode1v3 16 | *.mode2v3 17 | !default.mode2v3 18 | *.perspectivev3 19 | !default.perspectivev3 20 | xcuserdata/ 21 | 22 | ## Other 23 | *.moved-aside 24 | *.xccheckout 25 | *.xcscmblueprint 26 | 27 | #Idea 28 | .idea/ 29 | .idea 30 | 31 | ## Obj-C/Swift specific 32 | *.hmap 33 | *.ipa 34 | *.dSYM.zip 35 | *.dSYM 36 | 37 | # CocoaPods 38 | # 39 | # We recommend against adding the Pods directory to your .gitignore. However 40 | # you should judge for yourself, the pros and cons are mentioned at: 41 | # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control 42 | # 43 | Pods/ 44 | 45 | # Carthage 46 | # 47 | # Add this line if you want to avoid checking in source code from Carthage dependencies. 48 | Carthage/Checkouts 49 | 50 | Carthage/Build 51 | 52 | # fastlane 53 | # 54 | # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the 55 | # screenshots whenever they are needed. 56 | # For more information about the recommended setup visit: 57 | # https://docs.fastlane.tools/best-practices/source-control/#source-control 58 | 59 | fastlane/report.xml 60 | fastlane/Preview.html 61 | fastlane/screenshots 62 | fastlane/test_output 63 | 64 | .build 65 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ![WebSocket](https://github.com/appspector/URLSessionWebSocketTask/raw/master/images/websocket.jpg) 2 | # URLSessionWebSocketTask sample project 3 | 4 | This is a sample project for new URLSessionWebSocketTask API introduced in iOS 13. 5 | 6 | This project is using SwiftNIO as echo websocket server. 7 | -------------------------------------------------------------------------------- /WSServer/.buildzz/Package.resolved: -------------------------------------------------------------------------------- 1 | { 2 | "object": { 3 | "pins": [ 4 | { 5 | "package": "swift-nio", 6 | "repositoryURL": "https://github.com/apple/swift-nio.git", 7 | "state": { 8 | "branch": null, 9 | "revision": "ba7970fe396e8198b84c6c1b44b38a1d4e2eb6bd", 10 | "version": "1.14.1" 11 | } 12 | }, 13 | { 14 | "package": "swift-nio-zlib-support", 15 | "repositoryURL": "https://github.com/apple/swift-nio-zlib-support.git", 16 | "state": { 17 | "branch": null, 18 | "revision": "37760e9a52030bb9011972c5213c3350fa9d41fd", 19 | "version": "1.0.0" 20 | } 21 | } 22 | ] 23 | }, 24 | "version": 1 25 | } 26 | -------------------------------------------------------------------------------- /WSServer/.buildzz/Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version:4.0 2 | // 3 | // Package.swift 4 | // WSServer 5 | // 6 | // Created by zen on 7/1/19. 7 | // Copyright © 2019 AppSpector. All rights reserved. 8 | // 9 | import PackageDescription 10 | 11 | let package = Package( 12 | name: "WSServer", 13 | 14 | dependencies: [ 15 | .package(url: "https://github.com/apple/swift-nio.git", 16 | from: "1.9.4"), 17 | ], 18 | 19 | targets: [ 20 | .target(name: "WSServer", 21 | dependencies: [ 22 | /* Add your target dependencies in here, e.g.: */ 23 | // "cows", 24 | "NIO", 25 | "NIOHTTP1", 26 | ]) 27 | ] 28 | ) 29 | -------------------------------------------------------------------------------- /WSServer/.buildzz/Sources/WSServer/dummy.swift: -------------------------------------------------------------------------------- 1 | fileprivate let swiftXcodeDummy = true; 2 | -------------------------------------------------------------------------------- /WSServer/Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version:4.0 2 | // 3 | // Package.swift 4 | // WSServer 5 | // 6 | // Created by zen on 7/1/19. 7 | // Copyright © 2019 AppSpector. All rights reserved. 8 | // 9 | import PackageDescription 10 | 11 | let package = Package( 12 | name: "WSServer", 13 | 14 | dependencies: [ 15 | .package(url: "https://github.com/apple/swift-nio.git", 16 | from: "1.9.4"), 17 | ], 18 | 19 | targets: [ 20 | .target(name: "WSServer", 21 | dependencies: [ 22 | /* Add your target dependencies in here, e.g.: */ 23 | // "cows", 24 | "NIO", 25 | "NIOHTTP1", 26 | ]) 27 | ] 28 | ) 29 | -------------------------------------------------------------------------------- /WSServer/Sources/WSServer/main.swift: -------------------------------------------------------------------------------- 1 | // 2 | // main.swift 3 | // Server 4 | // 5 | // Created by zen on 2/23/19. 6 | // Copyright © 2019 AppSpector. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | import NIO 11 | import NIOHTTP1 12 | import NIOWebSocket 13 | 14 | class WebSocketHandler : ChannelInboundHandler { 15 | 16 | typealias InboundIn = WebSocketFrame 17 | typealias OutboundOut = WebSocketFrame 18 | 19 | private var awaitingClose: Bool = false 20 | 21 | func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { 22 | let frame = unwrapInboundIn(data) 23 | 24 | switch frame.opcode { 25 | case .connectionClose: 26 | self.receivedClose(ctx: ctx, frame: frame) 27 | case .ping: 28 | self.pong(ctx: ctx, frame: frame) 29 | case .text: 30 | var data = frame.unmaskedData 31 | let payload = data.readString(length: data.readableBytes) ?? "" 32 | handlePayload(ctx: ctx, payload: payload) 33 | default: 34 | return 35 | } 36 | } 37 | 38 | func handlePayload(ctx: ChannelHandlerContext, payload: String) { 39 | var buffer = ctx.channel.allocator.buffer(capacity: payload.utf8.count) 40 | buffer.write(string: payload) 41 | 42 | let frame = WebSocketFrame(fin: true, opcode: .text, data: buffer) 43 | 44 | _ = ctx.channel.writeAndFlush(frame) 45 | } 46 | 47 | func channelReadComplete(ctx: ChannelHandlerContext) { 48 | ctx.flush() 49 | } 50 | 51 | func channelActive(ctx: ChannelHandlerContext) { 52 | print("Channel ready, client address:", ctx.channel.remoteAddress?.description ?? "-") 53 | } 54 | 55 | func channelInactive(ctx: ChannelHandlerContext) { 56 | print("Channel closed.", ObjectIdentifier(self)) 57 | } 58 | 59 | func errorCaught(ctx: ChannelHandlerContext, error: Error) { 60 | print("ERROR:", error) 61 | ctx.close(promise: nil) 62 | } 63 | 64 | private func pong(ctx: ChannelHandlerContext, frame: WebSocketFrame) { 65 | var frameData = frame.data 66 | let maskingKey = frame.maskKey 67 | 68 | if let maskingKey = maskingKey { 69 | frameData.webSocketUnmask(maskingKey) 70 | } 71 | 72 | let responseFrame = WebSocketFrame(fin: true, opcode: .pong, data: frameData) 73 | ctx.write(self.wrapOutboundOut(responseFrame), promise: nil) 74 | } 75 | 76 | private func receivedClose(ctx: ChannelHandlerContext, frame: WebSocketFrame) { 77 | // Handle a received close frame. In websockets, we're just going to send the close 78 | // frame and then close, unless we already sent our own close frame. 79 | if awaitingClose { 80 | // Cool, we started the close and were waiting for the user. We're done. 81 | ctx.close(promise: nil) 82 | } else { 83 | // This is an unsolicited close. We're going to send a response frame and 84 | // then, when we've sent it, close up shop. We should send back the close code the remote 85 | // peer sent us, unless they didn't send one at all. 86 | var data = frame.unmaskedData 87 | let closeDataCode = data.readSlice(length: 2) ?? ctx.channel.allocator.buffer(capacity: 0) 88 | let closeFrame = WebSocketFrame(fin: true, opcode: .connectionClose, data: closeDataCode) 89 | _ = ctx.write(self.wrapOutboundOut(closeFrame)).map { () in 90 | ctx.close(promise: nil) 91 | } 92 | } 93 | } 94 | } 95 | 96 | final class Server { 97 | 98 | struct Configuration { 99 | var host : String? = nil 100 | var port : Int = 8080 101 | var backlog : Int = 256 102 | var eventLoopGroup : EventLoopGroup? = nil 103 | } 104 | 105 | let configuration : Configuration 106 | let eventLoopGroup : EventLoopGroup 107 | var serverChannel : Channel? 108 | 109 | init(configuration: Configuration = Configuration()) { 110 | self.configuration = configuration 111 | self.eventLoopGroup = configuration.eventLoopGroup ?? MultiThreadedEventLoopGroup(numberOfThreads: 1) 112 | } 113 | 114 | func listenAndWait() { 115 | listen() 116 | 117 | do { 118 | try serverChannel?.closeFuture.wait() 119 | } 120 | catch { 121 | print("ERROR: Failed to wait on server:", error) 122 | } 123 | } 124 | 125 | func listen() { 126 | 127 | let bootstrap = makeBootstrap() 128 | 129 | do { 130 | let address : SocketAddress 131 | 132 | if let host = configuration.host { 133 | address = try SocketAddress.newAddressResolving(host: host, port: configuration.port) 134 | } else { 135 | var addr = sockaddr_in() 136 | addr.sin_port = in_port_t(configuration.port).bigEndian 137 | address = SocketAddress(addr, host: "*") 138 | } 139 | 140 | serverChannel = try bootstrap.bind(to: address).wait() 141 | 142 | if let addr = serverChannel?.localAddress { 143 | print("Server running on:", addr) 144 | } 145 | else { 146 | print("ERROR: server reported no local address?") 147 | } 148 | } 149 | catch let error as NIO.IOError { 150 | print("ERROR: failed to start server, errno:", error.errnoCode, "\n", error.localizedDescription) 151 | } 152 | catch { 153 | print("ERROR: failed to start server:", type(of:error), error) 154 | } 155 | } 156 | 157 | func shouldUpgrade(head: HTTPRequestHead) -> HTTPHeaders? { 158 | if (head.uri.starts(with: "/echo")) { 159 | return HTTPHeaders() 160 | } 161 | 162 | return nil 163 | } 164 | 165 | func upgradePipelineHandler(channel: Channel, head: HTTPRequestHead) -> NIO.EventLoopFuture { 166 | if (head.uri.starts(with: "/echo")) { 167 | return channel.pipeline.add(handler: WebSocketHandler()) 168 | } 169 | 170 | return channel.closeFuture 171 | } 172 | 173 | func makeBootstrap() -> ServerBootstrap { 174 | let reuseAddrOpt = ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR) 175 | let bootstrap = ServerBootstrap(group: eventLoopGroup) 176 | .serverChannelOption(ChannelOptions.backlog, value: Int32(configuration.backlog)) 177 | .serverChannelOption(reuseAddrOpt, value: 1) 178 | .childChannelInitializer { channel in 179 | let connectionUpgrader = WebSocketUpgrader(shouldUpgrade: self.shouldUpgrade, upgradePipelineHandler: self.upgradePipelineHandler) 180 | 181 | let config: HTTPUpgradeConfiguration = ( 182 | upgraders: [ connectionUpgrader ], 183 | completionHandler: { _ in } 184 | ) 185 | 186 | return channel.pipeline.configureHTTPServerPipeline(first: true, withPipeliningAssistance: true, withServerUpgrade: config, withErrorHandling: true) 187 | 188 | } 189 | .childChannelOption(ChannelOptions.socket(IPPROTO_TCP, TCP_NODELAY), value: 1) 190 | .childChannelOption(reuseAddrOpt, value: 1) 191 | .childChannelOption(ChannelOptions.maxMessagesPerRead, value: 1) 192 | 193 | return bootstrap 194 | } 195 | } 196 | 197 | 198 | // MARK: - Start and run Server 199 | 200 | let server = Server() 201 | server.listenAndWait() 202 | -------------------------------------------------------------------------------- /WebSockets.xcodeproj/project.pbxproj: -------------------------------------------------------------------------------- 1 | // !$*UTF8*$! 2 | { 3 | archiveVersion = 1; 4 | classes = { 5 | }; 6 | objectVersion = 52; 7 | objects = { 8 | 9 | /* Begin PBXBuildFile section */ 10 | AD10D2E522B7E1BD006AABAB /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = AD10D2E422B7E1BD006AABAB /* AppDelegate.swift */; }; 11 | AD10D2E722B7E1BD006AABAB /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = AD10D2E622B7E1BD006AABAB /* SceneDelegate.swift */; }; 12 | AD10D2E922B7E1BD006AABAB /* ContentView.swift in Sources */ = {isa = PBXBuildFile; fileRef = AD10D2E822B7E1BD006AABAB /* ContentView.swift */; }; 13 | AD10D2EB22B7E1BF006AABAB /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = AD10D2EA22B7E1BF006AABAB /* Assets.xcassets */; }; 14 | AD10D2EE22B7E1BF006AABAB /* Preview Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = AD10D2ED22B7E1BF006AABAB /* Preview Assets.xcassets */; }; 15 | AD10D2F122B7E1BF006AABAB /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = AD10D2EF22B7E1BF006AABAB /* LaunchScreen.storyboard */; }; 16 | AD10D2F922B7E237006AABAB /* WebSocketConnection.swift in Sources */ = {isa = PBXBuildFile; fileRef = AD10D2F822B7E237006AABAB /* WebSocketConnection.swift */; }; 17 | AD95920922CA612F003E995D /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = AD95920822CA612F003E995D /* main.swift */; }; 18 | AD95921022CA619A003E995D /* NIOWebSocket in Frameworks */ = {isa = PBXBuildFile; productRef = AD95920F22CA619A003E995D /* NIOWebSocket */; }; 19 | AD95921222CA619A003E995D /* NIO in Frameworks */ = {isa = PBXBuildFile; productRef = AD95921122CA619A003E995D /* NIO */; }; 20 | AD95921522CA61AF003E995D /* NIOHTTP1 in Frameworks */ = {isa = PBXBuildFile; productRef = AD95921422CA61AF003E995D /* NIOHTTP1 */; }; 21 | /* End PBXBuildFile section */ 22 | 23 | /* Begin PBXFileReference section */ 24 | AD10D2E122B7E1BD006AABAB /* WebSockets.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = WebSockets.app; sourceTree = BUILT_PRODUCTS_DIR; }; 25 | AD10D2E422B7E1BD006AABAB /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 26 | AD10D2E622B7E1BD006AABAB /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; 27 | AD10D2E822B7E1BD006AABAB /* ContentView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContentView.swift; sourceTree = ""; }; 28 | AD10D2EA22B7E1BF006AABAB /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 29 | AD10D2ED22B7E1BF006AABAB /* Preview Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = "Preview Assets.xcassets"; sourceTree = ""; }; 30 | AD10D2F022B7E1BF006AABAB /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 31 | AD10D2F222B7E1BF006AABAB /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 32 | AD10D2F822B7E237006AABAB /* WebSocketConnection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WebSocketConnection.swift; sourceTree = ""; }; 33 | AD95920622CA612F003E995D /* WSServer */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = WSServer; sourceTree = BUILT_PRODUCTS_DIR; }; 34 | AD95920822CA612F003E995D /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = main.swift; path = Sources/WSServer/main.swift; sourceTree = ""; }; 35 | AD95920A22CA612F003E995D /* Package.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Package.swift; sourceTree = ""; }; 36 | /* End PBXFileReference section */ 37 | 38 | /* Begin PBXFrameworksBuildPhase section */ 39 | AD10D2DE22B7E1BD006AABAB /* Frameworks */ = { 40 | isa = PBXFrameworksBuildPhase; 41 | buildActionMask = 2147483647; 42 | files = ( 43 | ); 44 | runOnlyForDeploymentPostprocessing = 0; 45 | }; 46 | AD95920422CA612F003E995D /* Frameworks */ = { 47 | isa = PBXFrameworksBuildPhase; 48 | buildActionMask = 2147483647; 49 | files = ( 50 | AD95921522CA61AF003E995D /* NIOHTTP1 in Frameworks */, 51 | AD95921022CA619A003E995D /* NIOWebSocket in Frameworks */, 52 | AD95921222CA619A003E995D /* NIO in Frameworks */, 53 | ); 54 | runOnlyForDeploymentPostprocessing = 0; 55 | }; 56 | /* End PBXFrameworksBuildPhase section */ 57 | 58 | /* Begin PBXGroup section */ 59 | AD10D2D822B7E1BD006AABAB = { 60 | isa = PBXGroup; 61 | children = ( 62 | AD10D2E322B7E1BD006AABAB /* WebSockets */, 63 | AD95920722CA612F003E995D /* WSServer */, 64 | AD10D2E222B7E1BD006AABAB /* Products */, 65 | AD95921322CA61AF003E995D /* Frameworks */, 66 | ); 67 | sourceTree = ""; 68 | }; 69 | AD10D2E222B7E1BD006AABAB /* Products */ = { 70 | isa = PBXGroup; 71 | children = ( 72 | AD10D2E122B7E1BD006AABAB /* WebSockets.app */, 73 | AD95920622CA612F003E995D /* WSServer */, 74 | ); 75 | name = Products; 76 | sourceTree = ""; 77 | }; 78 | AD10D2E322B7E1BD006AABAB /* WebSockets */ = { 79 | isa = PBXGroup; 80 | children = ( 81 | AD10D2E422B7E1BD006AABAB /* AppDelegate.swift */, 82 | AD10D2E622B7E1BD006AABAB /* SceneDelegate.swift */, 83 | AD10D2E822B7E1BD006AABAB /* ContentView.swift */, 84 | AD10D2EA22B7E1BF006AABAB /* Assets.xcassets */, 85 | AD10D2EF22B7E1BF006AABAB /* LaunchScreen.storyboard */, 86 | AD10D2F222B7E1BF006AABAB /* Info.plist */, 87 | AD10D2EC22B7E1BF006AABAB /* Preview Content */, 88 | AD10D2F822B7E237006AABAB /* WebSocketConnection.swift */, 89 | ); 90 | path = WebSockets; 91 | sourceTree = ""; 92 | }; 93 | AD10D2EC22B7E1BF006AABAB /* Preview Content */ = { 94 | isa = PBXGroup; 95 | children = ( 96 | AD10D2ED22B7E1BF006AABAB /* Preview Assets.xcassets */, 97 | ); 98 | path = "Preview Content"; 99 | sourceTree = ""; 100 | }; 101 | AD95920722CA612F003E995D /* WSServer */ = { 102 | isa = PBXGroup; 103 | children = ( 104 | AD95920822CA612F003E995D /* main.swift */, 105 | AD95920A22CA612F003E995D /* Package.swift */, 106 | ); 107 | path = WSServer; 108 | sourceTree = ""; 109 | }; 110 | AD95921322CA61AF003E995D /* Frameworks */ = { 111 | isa = PBXGroup; 112 | children = ( 113 | ); 114 | name = Frameworks; 115 | sourceTree = ""; 116 | }; 117 | /* End PBXGroup section */ 118 | 119 | /* Begin PBXNativeTarget section */ 120 | AD10D2E022B7E1BD006AABAB /* WebSockets */ = { 121 | isa = PBXNativeTarget; 122 | buildConfigurationList = AD10D2F522B7E1BF006AABAB /* Build configuration list for PBXNativeTarget "WebSockets" */; 123 | buildPhases = ( 124 | AD10D2DD22B7E1BD006AABAB /* Sources */, 125 | AD10D2DE22B7E1BD006AABAB /* Frameworks */, 126 | AD10D2DF22B7E1BD006AABAB /* Resources */, 127 | ); 128 | buildRules = ( 129 | ); 130 | dependencies = ( 131 | ); 132 | name = WebSockets; 133 | productName = WebSockets; 134 | productReference = AD10D2E122B7E1BD006AABAB /* WebSockets.app */; 135 | productType = "com.apple.product-type.application"; 136 | }; 137 | AD95920522CA612F003E995D /* WSServer */ = { 138 | isa = PBXNativeTarget; 139 | buildConfigurationList = AD95920D22CA612F003E995D /* Build configuration list for PBXNativeTarget "WSServer" */; 140 | buildPhases = ( 141 | AD95920222CA612F003E995D /* Build Swift Package Manager Dependencies */, 142 | AD95920322CA612F003E995D /* Sources */, 143 | AD95920422CA612F003E995D /* Frameworks */, 144 | ); 145 | buildRules = ( 146 | ); 147 | dependencies = ( 148 | ); 149 | name = WSServer; 150 | packageProductDependencies = ( 151 | AD95920F22CA619A003E995D /* NIOWebSocket */, 152 | AD95921122CA619A003E995D /* NIO */, 153 | AD95921422CA61AF003E995D /* NIOHTTP1 */, 154 | ); 155 | productName = WSServer; 156 | productReference = AD95920622CA612F003E995D /* WSServer */; 157 | productType = "com.apple.product-type.tool"; 158 | }; 159 | /* End PBXNativeTarget section */ 160 | 161 | /* Begin PBXProject section */ 162 | AD10D2D922B7E1BD006AABAB /* Project object */ = { 163 | isa = PBXProject; 164 | attributes = { 165 | LastSwiftUpdateCheck = 1100; 166 | LastUpgradeCheck = 1100; 167 | ORGANIZATIONNAME = AppSpector; 168 | TargetAttributes = { 169 | AD10D2E022B7E1BD006AABAB = { 170 | CreatedOnToolsVersion = 11.0; 171 | }; 172 | AD95920522CA612F003E995D = { 173 | CreatedOnToolsVersion = 11.0; 174 | }; 175 | }; 176 | }; 177 | buildConfigurationList = AD10D2DC22B7E1BD006AABAB /* Build configuration list for PBXProject "WebSockets" */; 178 | compatibilityVersion = "Xcode 9.3"; 179 | developmentRegion = en; 180 | hasScannedForEncodings = 0; 181 | knownRegions = ( 182 | en, 183 | Base, 184 | ); 185 | mainGroup = AD10D2D822B7E1BD006AABAB; 186 | packageReferences = ( 187 | AD95920E22CA619A003E995D /* XCRemoteSwiftPackageReference "swift-nio" */, 188 | ); 189 | productRefGroup = AD10D2E222B7E1BD006AABAB /* Products */; 190 | projectDirPath = ""; 191 | projectRoot = ""; 192 | targets = ( 193 | AD10D2E022B7E1BD006AABAB /* WebSockets */, 194 | AD95920522CA612F003E995D /* WSServer */, 195 | ); 196 | }; 197 | /* End PBXProject section */ 198 | 199 | /* Begin PBXResourcesBuildPhase section */ 200 | AD10D2DF22B7E1BD006AABAB /* Resources */ = { 201 | isa = PBXResourcesBuildPhase; 202 | buildActionMask = 2147483647; 203 | files = ( 204 | AD10D2F122B7E1BF006AABAB /* LaunchScreen.storyboard in Resources */, 205 | AD10D2EE22B7E1BF006AABAB /* Preview Assets.xcassets in Resources */, 206 | AD10D2EB22B7E1BF006AABAB /* Assets.xcassets in Resources */, 207 | ); 208 | runOnlyForDeploymentPostprocessing = 0; 209 | }; 210 | /* End PBXResourcesBuildPhase section */ 211 | 212 | /* Begin PBXShellScriptBuildPhase section */ 213 | AD95920222CA612F003E995D /* Build Swift Package Manager Dependencies */ = { 214 | isa = PBXShellScriptBuildPhase; 215 | buildActionMask = 2147483647; 216 | files = ( 217 | ); 218 | inputFileListPaths = ( 219 | ); 220 | inputPaths = ( 221 | ); 222 | name = "Build Swift Package Manager Dependencies"; 223 | outputFileListPaths = ( 224 | ); 225 | outputPaths = ( 226 | ); 227 | runOnlyForDeploymentPostprocessing = 0; 228 | shellPath = /bin/sh; 229 | shellScript = "SPM_IMAGE=SwiftNIO verbose=no swift xcode build"; 230 | }; 231 | /* End PBXShellScriptBuildPhase section */ 232 | 233 | /* Begin PBXSourcesBuildPhase section */ 234 | AD10D2DD22B7E1BD006AABAB /* Sources */ = { 235 | isa = PBXSourcesBuildPhase; 236 | buildActionMask = 2147483647; 237 | files = ( 238 | AD10D2E522B7E1BD006AABAB /* AppDelegate.swift in Sources */, 239 | AD10D2E722B7E1BD006AABAB /* SceneDelegate.swift in Sources */, 240 | AD10D2E922B7E1BD006AABAB /* ContentView.swift in Sources */, 241 | AD10D2F922B7E237006AABAB /* WebSocketConnection.swift in Sources */, 242 | ); 243 | runOnlyForDeploymentPostprocessing = 0; 244 | }; 245 | AD95920322CA612F003E995D /* Sources */ = { 246 | isa = PBXSourcesBuildPhase; 247 | buildActionMask = 2147483647; 248 | files = ( 249 | AD95920922CA612F003E995D /* main.swift in Sources */, 250 | ); 251 | runOnlyForDeploymentPostprocessing = 0; 252 | }; 253 | /* End PBXSourcesBuildPhase section */ 254 | 255 | /* Begin PBXVariantGroup section */ 256 | AD10D2EF22B7E1BF006AABAB /* LaunchScreen.storyboard */ = { 257 | isa = PBXVariantGroup; 258 | children = ( 259 | AD10D2F022B7E1BF006AABAB /* Base */, 260 | ); 261 | name = LaunchScreen.storyboard; 262 | sourceTree = ""; 263 | }; 264 | /* End PBXVariantGroup section */ 265 | 266 | /* Begin XCBuildConfiguration section */ 267 | AD10D2F322B7E1BF006AABAB /* Debug */ = { 268 | isa = XCBuildConfiguration; 269 | buildSettings = { 270 | ALWAYS_SEARCH_USER_PATHS = NO; 271 | CLANG_ANALYZER_NONNULL = YES; 272 | CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; 273 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; 274 | CLANG_CXX_LIBRARY = "libc++"; 275 | CLANG_ENABLE_MODULES = YES; 276 | CLANG_ENABLE_OBJC_ARC = YES; 277 | CLANG_ENABLE_OBJC_WEAK = YES; 278 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; 279 | CLANG_WARN_BOOL_CONVERSION = YES; 280 | CLANG_WARN_COMMA = YES; 281 | CLANG_WARN_CONSTANT_CONVERSION = YES; 282 | CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; 283 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 284 | CLANG_WARN_DOCUMENTATION_COMMENTS = YES; 285 | CLANG_WARN_EMPTY_BODY = YES; 286 | CLANG_WARN_ENUM_CONVERSION = YES; 287 | CLANG_WARN_INFINITE_RECURSION = YES; 288 | CLANG_WARN_INT_CONVERSION = YES; 289 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; 290 | CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; 291 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; 292 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 293 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; 294 | CLANG_WARN_STRICT_PROTOTYPES = YES; 295 | CLANG_WARN_SUSPICIOUS_MOVE = YES; 296 | CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; 297 | CLANG_WARN_UNREACHABLE_CODE = YES; 298 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 299 | COPY_PHASE_STRIP = NO; 300 | DEBUG_INFORMATION_FORMAT = dwarf; 301 | ENABLE_STRICT_OBJC_MSGSEND = YES; 302 | ENABLE_TESTABILITY = YES; 303 | GCC_C_LANGUAGE_STANDARD = gnu11; 304 | GCC_DYNAMIC_NO_PIC = NO; 305 | GCC_NO_COMMON_BLOCKS = YES; 306 | GCC_OPTIMIZATION_LEVEL = 0; 307 | GCC_PREPROCESSOR_DEFINITIONS = ( 308 | "DEBUG=1", 309 | "$(inherited)", 310 | ); 311 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 312 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 313 | GCC_WARN_UNDECLARED_SELECTOR = YES; 314 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 315 | GCC_WARN_UNUSED_FUNCTION = YES; 316 | GCC_WARN_UNUSED_VARIABLE = YES; 317 | IPHONEOS_DEPLOYMENT_TARGET = 13.0; 318 | MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; 319 | MTL_FAST_MATH = YES; 320 | ONLY_ACTIVE_ARCH = YES; 321 | SDKROOT = iphoneos; 322 | SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; 323 | SWIFT_OPTIMIZATION_LEVEL = "-Onone"; 324 | }; 325 | name = Debug; 326 | }; 327 | AD10D2F422B7E1BF006AABAB /* Release */ = { 328 | isa = XCBuildConfiguration; 329 | buildSettings = { 330 | ALWAYS_SEARCH_USER_PATHS = NO; 331 | CLANG_ANALYZER_NONNULL = YES; 332 | CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; 333 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; 334 | CLANG_CXX_LIBRARY = "libc++"; 335 | CLANG_ENABLE_MODULES = YES; 336 | CLANG_ENABLE_OBJC_ARC = YES; 337 | CLANG_ENABLE_OBJC_WEAK = YES; 338 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; 339 | CLANG_WARN_BOOL_CONVERSION = YES; 340 | CLANG_WARN_COMMA = YES; 341 | CLANG_WARN_CONSTANT_CONVERSION = YES; 342 | CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; 343 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 344 | CLANG_WARN_DOCUMENTATION_COMMENTS = YES; 345 | CLANG_WARN_EMPTY_BODY = YES; 346 | CLANG_WARN_ENUM_CONVERSION = YES; 347 | CLANG_WARN_INFINITE_RECURSION = YES; 348 | CLANG_WARN_INT_CONVERSION = YES; 349 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; 350 | CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; 351 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; 352 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 353 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; 354 | CLANG_WARN_STRICT_PROTOTYPES = YES; 355 | CLANG_WARN_SUSPICIOUS_MOVE = YES; 356 | CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; 357 | CLANG_WARN_UNREACHABLE_CODE = YES; 358 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 359 | COPY_PHASE_STRIP = NO; 360 | DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; 361 | ENABLE_NS_ASSERTIONS = NO; 362 | ENABLE_STRICT_OBJC_MSGSEND = YES; 363 | GCC_C_LANGUAGE_STANDARD = gnu11; 364 | GCC_NO_COMMON_BLOCKS = YES; 365 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 366 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 367 | GCC_WARN_UNDECLARED_SELECTOR = YES; 368 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 369 | GCC_WARN_UNUSED_FUNCTION = YES; 370 | GCC_WARN_UNUSED_VARIABLE = YES; 371 | IPHONEOS_DEPLOYMENT_TARGET = 13.0; 372 | MTL_ENABLE_DEBUG_INFO = NO; 373 | MTL_FAST_MATH = YES; 374 | SDKROOT = iphoneos; 375 | SWIFT_COMPILATION_MODE = wholemodule; 376 | SWIFT_OPTIMIZATION_LEVEL = "-O"; 377 | VALIDATE_PRODUCT = YES; 378 | }; 379 | name = Release; 380 | }; 381 | AD10D2F622B7E1BF006AABAB /* Debug */ = { 382 | isa = XCBuildConfiguration; 383 | buildSettings = { 384 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; 385 | CODE_SIGN_STYLE = Automatic; 386 | DEVELOPMENT_ASSET_PATHS = "WebSockets/Preview\\ Content"; 387 | DEVELOPMENT_TEAM = EEJA65ZWYD; 388 | ENABLE_PREVIEWS = YES; 389 | INFOPLIST_FILE = WebSockets/Info.plist; 390 | LD_RUNPATH_SEARCH_PATHS = ( 391 | "$(inherited)", 392 | "@executable_path/Frameworks", 393 | ); 394 | PRODUCT_BUNDLE_IDENTIFIER = com.appspector.WebSockets; 395 | PRODUCT_NAME = "$(TARGET_NAME)"; 396 | SWIFT_VERSION = 5.0; 397 | TARGETED_DEVICE_FAMILY = "1,2"; 398 | }; 399 | name = Debug; 400 | }; 401 | AD10D2F722B7E1BF006AABAB /* Release */ = { 402 | isa = XCBuildConfiguration; 403 | buildSettings = { 404 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; 405 | CODE_SIGN_STYLE = Automatic; 406 | DEVELOPMENT_ASSET_PATHS = "WebSockets/Preview\\ Content"; 407 | DEVELOPMENT_TEAM = EEJA65ZWYD; 408 | ENABLE_PREVIEWS = YES; 409 | INFOPLIST_FILE = WebSockets/Info.plist; 410 | LD_RUNPATH_SEARCH_PATHS = ( 411 | "$(inherited)", 412 | "@executable_path/Frameworks", 413 | ); 414 | PRODUCT_BUNDLE_IDENTIFIER = com.appspector.WebSockets; 415 | PRODUCT_NAME = "$(TARGET_NAME)"; 416 | SWIFT_VERSION = 5.0; 417 | TARGETED_DEVICE_FAMILY = "1,2"; 418 | }; 419 | name = Release; 420 | }; 421 | AD95920B22CA612F003E995D /* Debug */ = { 422 | isa = XCBuildConfiguration; 423 | buildSettings = { 424 | CODE_SIGN_STYLE = Automatic; 425 | DEVELOPMENT_TEAM = EEJA65ZWYD; 426 | ENABLE_HARDENED_RUNTIME = YES; 427 | HEADER_SEARCH_PATHS = "$(SRCROOT)/$(PRODUCT_NAME)/.buildzz/.build/Xcode/$(PLATFORM_PREFERRED_ARCH)-apple-$(SWIFT_PLATFORM_TARGET_PREFIX)$($(DEPLOYMENT_TARGET_SETTING_NAME))/$(CONFIGURATION)"; 428 | LIBRARY_SEARCH_PATHS = "$(SRCROOT)/$(PRODUCT_NAME)/.buildzz/.build/Xcode/$(PLATFORM_PREFERRED_ARCH)-apple-$(SWIFT_PLATFORM_TARGET_PREFIX)$($(DEPLOYMENT_TARGET_SETTING_NAME))/$(CONFIGURATION)"; 429 | MACOSX_DEPLOYMENT_TARGET = 10.15; 430 | OTHER_LDFLAGS = "-lXcodeSPMDependencies"; 431 | PRODUCT_NAME = "$(TARGET_NAME)"; 432 | SDKROOT = macosx; 433 | SWIFT_INCLUDE_PATHS = "$(SRCROOT)/$(PRODUCT_NAME)/.buildzz/.build/$(PLATFORM_PREFERRED_ARCH)-apple-$(SWIFT_PLATFORM_TARGET_PREFIX)$($(DEPLOYMENT_TARGET_SETTING_NAME))/$(CONFIGURATION)"; 434 | SWIFT_VERSION = 5.0; 435 | }; 436 | name = Debug; 437 | }; 438 | AD95920C22CA612F003E995D /* Release */ = { 439 | isa = XCBuildConfiguration; 440 | buildSettings = { 441 | CODE_SIGN_STYLE = Automatic; 442 | DEVELOPMENT_TEAM = EEJA65ZWYD; 443 | ENABLE_HARDENED_RUNTIME = YES; 444 | HEADER_SEARCH_PATHS = "$(SRCROOT)/$(PRODUCT_NAME)/.buildzz/.build/Xcode/$(PLATFORM_PREFERRED_ARCH)-apple-$(SWIFT_PLATFORM_TARGET_PREFIX)$($(DEPLOYMENT_TARGET_SETTING_NAME))/$(CONFIGURATION)"; 445 | LIBRARY_SEARCH_PATHS = "$(SRCROOT)/$(PRODUCT_NAME)/.buildzz/.build/Xcode/$(PLATFORM_PREFERRED_ARCH)-apple-$(SWIFT_PLATFORM_TARGET_PREFIX)$($(DEPLOYMENT_TARGET_SETTING_NAME))/$(CONFIGURATION)"; 446 | MACOSX_DEPLOYMENT_TARGET = 10.15; 447 | OTHER_LDFLAGS = "-lXcodeSPMDependencies"; 448 | PRODUCT_NAME = "$(TARGET_NAME)"; 449 | SDKROOT = macosx; 450 | SWIFT_INCLUDE_PATHS = "$(SRCROOT)/$(PRODUCT_NAME)/.buildzz/.build/$(PLATFORM_PREFERRED_ARCH)-apple-$(SWIFT_PLATFORM_TARGET_PREFIX)$($(DEPLOYMENT_TARGET_SETTING_NAME))/$(CONFIGURATION)"; 451 | SWIFT_VERSION = 5.0; 452 | }; 453 | name = Release; 454 | }; 455 | /* End XCBuildConfiguration section */ 456 | 457 | /* Begin XCConfigurationList section */ 458 | AD10D2DC22B7E1BD006AABAB /* Build configuration list for PBXProject "WebSockets" */ = { 459 | isa = XCConfigurationList; 460 | buildConfigurations = ( 461 | AD10D2F322B7E1BF006AABAB /* Debug */, 462 | AD10D2F422B7E1BF006AABAB /* Release */, 463 | ); 464 | defaultConfigurationIsVisible = 0; 465 | defaultConfigurationName = Release; 466 | }; 467 | AD10D2F522B7E1BF006AABAB /* Build configuration list for PBXNativeTarget "WebSockets" */ = { 468 | isa = XCConfigurationList; 469 | buildConfigurations = ( 470 | AD10D2F622B7E1BF006AABAB /* Debug */, 471 | AD10D2F722B7E1BF006AABAB /* Release */, 472 | ); 473 | defaultConfigurationIsVisible = 0; 474 | defaultConfigurationName = Release; 475 | }; 476 | AD95920D22CA612F003E995D /* Build configuration list for PBXNativeTarget "WSServer" */ = { 477 | isa = XCConfigurationList; 478 | buildConfigurations = ( 479 | AD95920B22CA612F003E995D /* Debug */, 480 | AD95920C22CA612F003E995D /* Release */, 481 | ); 482 | defaultConfigurationIsVisible = 0; 483 | defaultConfigurationName = Release; 484 | }; 485 | /* End XCConfigurationList section */ 486 | 487 | /* Begin XCRemoteSwiftPackageReference section */ 488 | AD95920E22CA619A003E995D /* XCRemoteSwiftPackageReference "swift-nio" */ = { 489 | isa = XCRemoteSwiftPackageReference; 490 | repositoryURL = "https://github.com/apple/swift-nio.git"; 491 | requirement = { 492 | kind = upToNextMajorVersion; 493 | minimumVersion = 1.9.4; 494 | }; 495 | }; 496 | /* End XCRemoteSwiftPackageReference section */ 497 | 498 | /* Begin XCSwiftPackageProductDependency section */ 499 | AD95920F22CA619A003E995D /* NIOWebSocket */ = { 500 | isa = XCSwiftPackageProductDependency; 501 | package = AD95920E22CA619A003E995D /* XCRemoteSwiftPackageReference "swift-nio" */; 502 | productName = NIOWebSocket; 503 | }; 504 | AD95921122CA619A003E995D /* NIO */ = { 505 | isa = XCSwiftPackageProductDependency; 506 | package = AD95920E22CA619A003E995D /* XCRemoteSwiftPackageReference "swift-nio" */; 507 | productName = NIO; 508 | }; 509 | AD95921422CA61AF003E995D /* NIOHTTP1 */ = { 510 | isa = XCSwiftPackageProductDependency; 511 | package = AD95920E22CA619A003E995D /* XCRemoteSwiftPackageReference "swift-nio" */; 512 | productName = NIOHTTP1; 513 | }; 514 | /* End XCSwiftPackageProductDependency section */ 515 | }; 516 | rootObject = AD10D2D922B7E1BD006AABAB /* Project object */; 517 | } 518 | -------------------------------------------------------------------------------- /WebSockets.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /WebSockets.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /WebSockets.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved: -------------------------------------------------------------------------------- 1 | { 2 | "object": { 3 | "pins": [ 4 | { 5 | "package": "swift-nio", 6 | "repositoryURL": "https://github.com/apple/swift-nio.git", 7 | "state": { 8 | "branch": null, 9 | "revision": "ba7970fe396e8198b84c6c1b44b38a1d4e2eb6bd", 10 | "version": "1.14.1" 11 | } 12 | }, 13 | { 14 | "package": "swift-nio-zlib-support", 15 | "repositoryURL": "https://github.com/apple/swift-nio-zlib-support.git", 16 | "state": { 17 | "branch": null, 18 | "revision": "37760e9a52030bb9011972c5213c3350fa9d41fd", 19 | "version": "1.0.0" 20 | } 21 | } 22 | ] 23 | }, 24 | "version": 1 25 | } 26 | -------------------------------------------------------------------------------- /WebSockets/AppDelegate.swift: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.swift 3 | // WebSockets 4 | // 5 | // Created by zen on 6/17/19. 6 | // Copyright © 2019 AppSpector. All rights reserved. 7 | // 8 | 9 | import UIKit 10 | 11 | @UIApplicationMain 12 | class AppDelegate: UIResponder, UIApplicationDelegate, WebSocketConnectionDelegate { 13 | func onConnected(connection: WebSocketConnection) { 14 | print("Connected") 15 | } 16 | 17 | func onDisconnected(connection: WebSocketConnection, error: Error?) { 18 | if let error = error { 19 | print("Disconnected with error:\(error)") 20 | } else { 21 | print("Disconnected normally") 22 | } 23 | } 24 | 25 | func onError(connection: WebSocketConnection, error: Error) { 26 | print("Connection error:\(error)") 27 | } 28 | 29 | func onMessage(connection: WebSocketConnection, text: String) { 30 | print("Text message: \(text)") 31 | DispatchQueue.main.asyncAfter(deadline: .now() + 1) { 32 | self.webSocketConnection.send(text: "ping") 33 | } 34 | } 35 | 36 | func onMessage(connection: WebSocketConnection, data: Data) { 37 | print("Data message: \(data)") 38 | } 39 | 40 | var webSocketConnection: WebSocketConnection! 41 | 42 | func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { 43 | webSocketConnection = WebSocketTaskConnection(url: URL(string: "ws://0.0.0.0:8080/echo")!) 44 | webSocketConnection.delegate = self 45 | 46 | webSocketConnection.connect() 47 | 48 | webSocketConnection.send(text: "ping") 49 | 50 | return true 51 | } 52 | // MARK: UISceneSession Lifecycle 53 | 54 | func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { 55 | // Called when a new scene session is being created. 56 | // Use this method to select a configuration to create the new scene with. 57 | return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) 58 | } 59 | 60 | } 61 | 62 | -------------------------------------------------------------------------------- /WebSockets/Assets.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "iphone", 5 | "size" : "20x20", 6 | "scale" : "2x" 7 | }, 8 | { 9 | "idiom" : "iphone", 10 | "size" : "20x20", 11 | "scale" : "3x" 12 | }, 13 | { 14 | "idiom" : "iphone", 15 | "size" : "29x29", 16 | "scale" : "2x" 17 | }, 18 | { 19 | "idiom" : "iphone", 20 | "size" : "29x29", 21 | "scale" : "3x" 22 | }, 23 | { 24 | "idiom" : "iphone", 25 | "size" : "40x40", 26 | "scale" : "2x" 27 | }, 28 | { 29 | "idiom" : "iphone", 30 | "size" : "40x40", 31 | "scale" : "3x" 32 | }, 33 | { 34 | "idiom" : "iphone", 35 | "size" : "60x60", 36 | "scale" : "2x" 37 | }, 38 | { 39 | "idiom" : "iphone", 40 | "size" : "60x60", 41 | "scale" : "3x" 42 | }, 43 | { 44 | "idiom" : "ipad", 45 | "size" : "20x20", 46 | "scale" : "1x" 47 | }, 48 | { 49 | "idiom" : "ipad", 50 | "size" : "20x20", 51 | "scale" : "2x" 52 | }, 53 | { 54 | "idiom" : "ipad", 55 | "size" : "29x29", 56 | "scale" : "1x" 57 | }, 58 | { 59 | "idiom" : "ipad", 60 | "size" : "29x29", 61 | "scale" : "2x" 62 | }, 63 | { 64 | "idiom" : "ipad", 65 | "size" : "40x40", 66 | "scale" : "1x" 67 | }, 68 | { 69 | "idiom" : "ipad", 70 | "size" : "40x40", 71 | "scale" : "2x" 72 | }, 73 | { 74 | "idiom" : "ipad", 75 | "size" : "76x76", 76 | "scale" : "1x" 77 | }, 78 | { 79 | "idiom" : "ipad", 80 | "size" : "76x76", 81 | "scale" : "2x" 82 | }, 83 | { 84 | "idiom" : "ipad", 85 | "size" : "83.5x83.5", 86 | "scale" : "2x" 87 | }, 88 | { 89 | "idiom" : "ios-marketing", 90 | "size" : "1024x1024", 91 | "scale" : "1x" 92 | } 93 | ], 94 | "info" : { 95 | "version" : 1, 96 | "author" : "xcode" 97 | } 98 | } -------------------------------------------------------------------------------- /WebSockets/Assets.xcassets/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "info" : { 3 | "version" : 1, 4 | "author" : "xcode" 5 | } 6 | } -------------------------------------------------------------------------------- /WebSockets/Base.lproj/LaunchScreen.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /WebSockets/ContentView.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ContentView.swift 3 | // WebSockets 4 | // 5 | // Created by zen on 6/17/19. 6 | // Copyright © 2019 AppSpector. All rights reserved. 7 | // 8 | 9 | import SwiftUI 10 | 11 | struct ContentView : View { 12 | var body: some View { 13 | Text("Hello World 2") 14 | } 15 | } 16 | 17 | #if DEBUG 18 | struct ContentView_Previews : PreviewProvider { 19 | static var previews: some View { 20 | ContentView() 21 | } 22 | } 23 | #endif 24 | -------------------------------------------------------------------------------- /WebSockets/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | $(DEVELOPMENT_LANGUAGE) 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | $(PRODUCT_BUNDLE_PACKAGE_TYPE) 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleVersion 20 | 1 21 | LSRequiresIPhoneOS 22 | 23 | UIApplicationSceneManifest 24 | 25 | UIApplicationSupportsMultipleScenes 26 | 27 | UISceneConfigurations 28 | 29 | UIWindowSceneSessionRoleApplication 30 | 31 | 32 | UILaunchStoryboardName 33 | LaunchScreen 34 | UISceneConfigurationName 35 | Default Configuration 36 | UISceneDelegateClassName 37 | $(PRODUCT_MODULE_NAME).SceneDelegate 38 | 39 | 40 | 41 | 42 | UILaunchStoryboardName 43 | LaunchScreen 44 | UIRequiredDeviceCapabilities 45 | 46 | armv7 47 | 48 | UISupportedInterfaceOrientations 49 | 50 | UIInterfaceOrientationPortrait 51 | UIInterfaceOrientationLandscapeLeft 52 | UIInterfaceOrientationLandscapeRight 53 | 54 | UISupportedInterfaceOrientations~ipad 55 | 56 | UIInterfaceOrientationPortrait 57 | UIInterfaceOrientationPortraitUpsideDown 58 | UIInterfaceOrientationLandscapeLeft 59 | UIInterfaceOrientationLandscapeRight 60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /WebSockets/Preview Content/Preview Assets.xcassets/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "info" : { 3 | "version" : 1, 4 | "author" : "xcode" 5 | } 6 | } -------------------------------------------------------------------------------- /WebSockets/SceneDelegate.swift: -------------------------------------------------------------------------------- 1 | // 2 | // SceneDelegate.swift 3 | // WebSockets 4 | // 5 | // Created by zen on 6/17/19. 6 | // Copyright © 2019 AppSpector. All rights reserved. 7 | // 8 | 9 | import UIKit 10 | import SwiftUI 11 | 12 | class SceneDelegate: UIResponder, UIWindowSceneDelegate { 13 | 14 | var window: UIWindow? 15 | 16 | 17 | func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { 18 | // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. 19 | // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. 20 | // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). 21 | 22 | // Use a UIHostingController as window root view controller 23 | let window = UIWindow(frame: UIScreen.main.bounds) 24 | window.rootViewController = UIHostingController(rootView: ContentView()) 25 | self.window = window 26 | window.makeKeyAndVisible() 27 | } 28 | 29 | func sceneDidDisconnect(_ scene: UIScene) { 30 | // Called as the scene is being released by the system. 31 | // This occurs shortly after the scene enters the background, or when its session is discarded. 32 | // Release any resources associated with this scene that can be re-created the next time the scene connects. 33 | // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). 34 | } 35 | 36 | func sceneDidBecomeActive(_ scene: UIScene) { 37 | // Called when the scene has moved from an inactive state to an active state. 38 | // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. 39 | } 40 | 41 | func sceneWillResignActive(_ scene: UIScene) { 42 | // Called when the scene will move from an active state to an inactive state. 43 | // This may occur due to temporary interruptions (ex. an incoming phone call). 44 | } 45 | 46 | func sceneWillEnterForeground(_ scene: UIScene) { 47 | // Called as the scene transitions from the background to the foreground. 48 | // Use this method to undo the changes made on entering the background. 49 | } 50 | 51 | func sceneDidEnterBackground(_ scene: UIScene) { 52 | // Called as the scene transitions from the foreground to the background. 53 | // Use this method to save data, release shared resources, and store enough scene-specific state information 54 | // to restore the scene back to its current state. 55 | } 56 | 57 | 58 | } 59 | 60 | -------------------------------------------------------------------------------- /WebSockets/WebSocketConnection.swift: -------------------------------------------------------------------------------- 1 | // 2 | // WebSocketConnection.swift 3 | // WebSockets 4 | // 5 | // Created by zen on 6/17/19. 6 | // Copyright © 2019 AppSpector. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | import Combine 11 | 12 | protocol WebSocketConnection { 13 | func send(text: String) 14 | func send(data: Data) 15 | func connect() 16 | func disconnect() 17 | var delegate: WebSocketConnectionDelegate? { 18 | get 19 | set 20 | } 21 | } 22 | 23 | protocol WebSocketConnectionDelegate { 24 | func onConnected(connection: WebSocketConnection) 25 | func onDisconnected(connection: WebSocketConnection, error: Error?) 26 | func onError(connection: WebSocketConnection, error: Error) 27 | func onMessage(connection: WebSocketConnection, text: String) 28 | func onMessage(connection: WebSocketConnection, data: Data) 29 | } 30 | 31 | class WebSocketTaskConnection: NSObject, WebSocketConnection, URLSessionWebSocketDelegate { 32 | var delegate: WebSocketConnectionDelegate? 33 | var webSocketTask: URLSessionWebSocketTask! 34 | var urlSession: URLSession! 35 | let delegateQueue = OperationQueue() 36 | 37 | init(url: URL) { 38 | super.init() 39 | urlSession = URLSession(configuration: .default, delegate: self, delegateQueue: delegateQueue) 40 | webSocketTask = urlSession.webSocketTask(with: url) 41 | } 42 | 43 | func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didOpenWithProtocol protocol: String?) { 44 | self.delegate?.onConnected(connection: self) 45 | } 46 | 47 | func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didCloseWith closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) { 48 | self.delegate?.onDisconnected(connection: self, error: nil) 49 | } 50 | 51 | func connect() { 52 | webSocketTask.resume() 53 | 54 | listen() 55 | } 56 | 57 | func disconnect() { 58 | webSocketTask.cancel(with: .goingAway, reason: nil) 59 | } 60 | 61 | func listen() { 62 | webSocketTask.receive { result in 63 | switch result { 64 | case .failure(let error): 65 | self.delegate?.onError(connection: self, error: error) 66 | case .success(let message): 67 | switch message { 68 | case .string(let text): 69 | self.delegate?.onMessage(connection: self, text: text) 70 | case .data(let data): 71 | self.delegate?.onMessage(connection: self, data: data) 72 | @unknown default: 73 | fatalError() 74 | } 75 | 76 | self.listen() 77 | } 78 | } 79 | } 80 | 81 | func send(text: String) { 82 | webSocketTask.send(URLSessionWebSocketTask.Message.string(text)) { error in 83 | if let error = error { 84 | self.delegate?.onError(connection: self, error: error) 85 | } 86 | } 87 | } 88 | 89 | func send(data: Data) { 90 | webSocketTask.send(URLSessionWebSocketTask.Message.data(data)) { error in 91 | if let error = error { 92 | self.delegate?.onError(connection: self, error: error) 93 | } 94 | } 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /images/websocket.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/appspector/URLSessionWebSocketTask/78014e8adcda0f39ad40fc8deeb4ae7497b96895/images/websocket.jpg --------------------------------------------------------------------------------