merge master
This commit is contained in:
commit
01e5e22e0b
@ -35,6 +35,8 @@ SocketIOClient* socket = [[SocketIOClient alloc] initWithSocketURL:@"localhost:8
|
|||||||
});
|
});
|
||||||
}];
|
}];
|
||||||
|
|
||||||
|
[socket connect];
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
##Features
|
##Features
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
Pod::Spec.new do |s|
|
Pod::Spec.new do |s|
|
||||||
s.name = "Socket.IO-Client-Swift"
|
s.name = "Socket.IO-Client-Swift"
|
||||||
s.version = "1.5.1"
|
s.version = "2.0.0"
|
||||||
s.summary = "Socket.IO-client for Swift"
|
s.summary = "Socket.IO-client for Swift"
|
||||||
s.description = <<-DESC
|
s.description = <<-DESC
|
||||||
Socket.IO-client for Swift.
|
Socket.IO-client for Swift.
|
||||||
@ -12,7 +12,7 @@ Pod::Spec.new do |s|
|
|||||||
s.author = { "Erik" => "nuclear.ace@gmail.com" }
|
s.author = { "Erik" => "nuclear.ace@gmail.com" }
|
||||||
s.ios.deployment_target = '8.0'
|
s.ios.deployment_target = '8.0'
|
||||||
s.osx.deployment_target = '10.10'
|
s.osx.deployment_target = '10.10'
|
||||||
s.source = { :git => "https://github.com/socketio/socket.io-client-swift.git", :tag => 'v1.5.1' }
|
s.source = { :git => "https://github.com/socketio/socket.io-client-swift.git", :tag => 'v2.0.0' }
|
||||||
s.source_files = "SwiftIO/**/*.swift"
|
s.source_files = "SwiftIO/**/*.swift"
|
||||||
s.requires_arc = true
|
s.requires_arc = true
|
||||||
# s.dependency 'Starscream', '~> 0.9' # currently this repo includes Starscream swift files
|
# s.dependency 'Starscream', '~> 0.9' # currently this repo includes Starscream swift files
|
||||||
|
|||||||
@ -24,9 +24,6 @@
|
|||||||
|
|
||||||
import Foundation
|
import Foundation
|
||||||
|
|
||||||
public typealias AckCallback = @objc_block (NSArray?) -> Void
|
|
||||||
public typealias OnAckCallback = (timeout:UInt64, callback:AckCallback) -> Void
|
|
||||||
|
|
||||||
struct SocketAckMap {
|
struct SocketAckMap {
|
||||||
private var acks = [Int: AckCallback]()
|
private var acks = [Int: AckCallback]()
|
||||||
private var waiting = [Int: Bool]()
|
private var waiting = [Int: Bool]()
|
||||||
|
|||||||
@ -26,24 +26,14 @@ import Foundation
|
|||||||
|
|
||||||
extension String {
|
extension String {
|
||||||
private var length:Int {
|
private var length:Int {
|
||||||
return countElements(self)
|
return count(self)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private typealias Probe = (msg:String, type:PacketType, data:ContiguousArray<NSData>?)
|
|
||||||
private typealias ProbeWaitQueue = [Probe]
|
|
||||||
|
|
||||||
public enum PacketType:String {
|
|
||||||
case OPEN = "0"
|
|
||||||
case CLOSE = "1"
|
|
||||||
case PING = "2"
|
|
||||||
case PONG = "3"
|
|
||||||
case MESSAGE = "4"
|
|
||||||
case UPGRADE = "5"
|
|
||||||
case NOOP = "6"
|
|
||||||
}
|
|
||||||
|
|
||||||
public class SocketEngine: NSObject, WebSocketDelegate {
|
public class SocketEngine: NSObject, WebSocketDelegate {
|
||||||
|
private typealias Probe = (msg:String, type:PacketType, data:ContiguousArray<NSData>?)
|
||||||
|
private typealias ProbeWaitQueue = [Probe]
|
||||||
|
|
||||||
private let workQueue = NSOperationQueue()
|
private let workQueue = NSOperationQueue()
|
||||||
private let emitQueue = dispatch_queue_create(
|
private let emitQueue = dispatch_queue_create(
|
||||||
"engineEmitQueue".cStringUsingEncoding(NSUTF8StringEncoding), DISPATCH_QUEUE_SERIAL)
|
"engineEmitQueue".cStringUsingEncoding(NSUTF8StringEncoding), DISPATCH_QUEUE_SERIAL)
|
||||||
@ -84,6 +74,24 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
|||||||
}
|
}
|
||||||
var ws:WebSocket?
|
var ws:WebSocket?
|
||||||
|
|
||||||
|
public enum PacketType:Int {
|
||||||
|
case OPEN = 0
|
||||||
|
case CLOSE = 1
|
||||||
|
case PING = 2
|
||||||
|
case PONG = 3
|
||||||
|
case MESSAGE = 4
|
||||||
|
case UPGRADE = 5
|
||||||
|
case NOOP = 6
|
||||||
|
|
||||||
|
init(str:String) {
|
||||||
|
if let value = str.toInt() {
|
||||||
|
self = PacketType(rawValue: value)!
|
||||||
|
} else {
|
||||||
|
self = PacketType.NOOP
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public init(client:SocketEngineClient, forcePolling:Bool,
|
public init(client:SocketEngineClient, forcePolling:Bool,
|
||||||
forceWebsockets:Bool, withCookies cookies:[NSHTTPCookie]?) {
|
forceWebsockets:Bool, withCookies cookies:[NSHTTPCookie]?) {
|
||||||
self.client = client
|
self.client = client
|
||||||
@ -147,7 +155,7 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
|||||||
urlWebSocket += "&\(keyEsc)="
|
urlWebSocket += "&\(keyEsc)="
|
||||||
|
|
||||||
if value is String {
|
if value is String {
|
||||||
let valueEsc = (value as String).stringByAddingPercentEncodingWithAllowedCharacters(
|
let valueEsc = (value as! String).stringByAddingPercentEncodingWithAllowedCharacters(
|
||||||
NSCharacterSet.URLHostAllowedCharacterSet())!
|
NSCharacterSet.URLHostAllowedCharacterSet())!
|
||||||
urlPolling += "\(valueEsc)"
|
urlPolling += "\(valueEsc)"
|
||||||
urlWebSocket += "\(valueEsc)"
|
urlWebSocket += "\(valueEsc)"
|
||||||
@ -227,6 +235,7 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
|||||||
}
|
}
|
||||||
|
|
||||||
self?.waitingForPoll = false
|
self?.waitingForPoll = false
|
||||||
|
|
||||||
if self!.fastUpgrade {
|
if self!.fastUpgrade {
|
||||||
self?.doFastUpgrade()
|
self?.doFastUpgrade()
|
||||||
return
|
return
|
||||||
@ -266,7 +275,7 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
|||||||
var postStr = ""
|
var postStr = ""
|
||||||
|
|
||||||
for packet in self.postWait {
|
for packet in self.postWait {
|
||||||
let len = countElements(packet)
|
let len = count(packet)
|
||||||
|
|
||||||
postStr += "\(len):\(packet)"
|
postStr += "\(len):\(packet)"
|
||||||
}
|
}
|
||||||
@ -320,6 +329,7 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// A poll failed, tell the client about it
|
// A poll failed, tell the client about it
|
||||||
|
|
||||||
private func handlePollingFailed(reason:String) {
|
private func handlePollingFailed(reason:String) {
|
||||||
self._connected = false
|
self._connected = false
|
||||||
self.ws?.disconnect()
|
self.ws?.disconnect()
|
||||||
@ -441,35 +451,24 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
|||||||
fixDoubleUTF8(&message)
|
fixDoubleUTF8(&message)
|
||||||
}
|
}
|
||||||
|
|
||||||
let type = message["^(\\d)"].groups()?[1]
|
let type = PacketType(str: (message["^(\\d)"].groups()?[1])!)
|
||||||
|
|
||||||
if type != PacketType.MESSAGE.rawValue {
|
if type == PacketType.MESSAGE {
|
||||||
// TODO Handle other packets
|
// Remove message type
|
||||||
if message.hasPrefix("b4") {
|
message.removeAtIndex(message.startIndex)
|
||||||
// binary in base64 string
|
|
||||||
|
|
||||||
message.removeRange(Range<String.Index>(start: message.startIndex,
|
|
||||||
end: advance(message.startIndex, 2)))
|
|
||||||
|
|
||||||
if let data = NSData(base64EncodedString: message,
|
|
||||||
options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters) {
|
|
||||||
// println("sending \(data)")
|
|
||||||
|
|
||||||
if self.client == nil {
|
if self.client == nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
dispatch_async(self.client!.handleQueue) {[weak self] in
|
dispatch_async(self.client!.handleQueue) {[weak self] in
|
||||||
self?.client?.parseBinaryData(data)
|
self?.client?.parseSocketMessage(message)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
} else if type == PacketType.NOOP {
|
||||||
|
|
||||||
return
|
|
||||||
} else if type == PacketType.NOOP.rawValue {
|
|
||||||
self.doPoll()
|
self.doPoll()
|
||||||
return
|
return
|
||||||
} else if type == PacketType.PONG.rawValue {
|
} else if type == PacketType.PONG {
|
||||||
// We should upgrade
|
// We should upgrade
|
||||||
if message == "3probe" {
|
if message == "3probe" {
|
||||||
self.upgradeTransport()
|
self.upgradeTransport()
|
||||||
@ -477,7 +476,7 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return
|
return
|
||||||
} else if type == PacketType.OPEN.rawValue {
|
} else if type == PacketType.OPEN {
|
||||||
var err:NSError?
|
var err:NSError?
|
||||||
|
|
||||||
message.removeAtIndex(message.startIndex)
|
message.removeAtIndex(message.startIndex)
|
||||||
@ -493,7 +492,7 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
|||||||
self.createWebsocket(andConnect: true)
|
self.createWebsocket(andConnect: true)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
self.client?.engineDidError("Error parsing engine connect")
|
NSLog("Error handshaking")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -501,8 +500,7 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
|||||||
self.pingInterval = pingInterval / 1000
|
self.pingInterval = pingInterval / 1000
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
self.client?.engineDidError("Error parsing engine connect")
|
fatalError("Error parsing engine connect")
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
self.startPingTimer()
|
self.startPingTimer()
|
||||||
@ -512,7 +510,7 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return
|
return
|
||||||
} else if type == PacketType.CLOSE.rawValue {
|
} else if type == PacketType.CLOSE {
|
||||||
if self.client == nil {
|
if self.client == nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@ -522,23 +520,26 @@ public class SocketEngine: NSObject, WebSocketDelegate {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
} else {
|
||||||
// println("Got something idk what to do with")
|
if message.hasPrefix("b4") {
|
||||||
// println(messageString)
|
// binary in base64 string
|
||||||
}
|
|
||||||
|
|
||||||
// Remove message type
|
message.removeRange(Range<String.Index>(start: message.startIndex,
|
||||||
message.removeAtIndex(message.startIndex)
|
end: advance(message.startIndex, 2)))
|
||||||
|
|
||||||
if self.client == nil {
|
if let data = NSData(base64EncodedString: message,
|
||||||
return
|
options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)
|
||||||
}
|
where self.client != nil {
|
||||||
|
// println("sending \(data)")
|
||||||
|
|
||||||
dispatch_async(self.client!.handleQueue) {[weak self] in
|
dispatch_async(self.client!.handleQueue) {[weak self] in
|
||||||
self?.client?.parseSocketMessage(message)
|
self?.client?.parseBinaryData(data)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private func probeWebSocket() {
|
private func probeWebSocket() {
|
||||||
if self.websocketConnected {
|
if self.websocketConnected {
|
||||||
|
|||||||
@ -24,9 +24,6 @@
|
|||||||
|
|
||||||
import Foundation
|
import Foundation
|
||||||
|
|
||||||
public typealias NormalCallback = (NSArray?, AckEmitter?) -> Void
|
|
||||||
public typealias AckEmitter = (AnyObject...) -> Void
|
|
||||||
|
|
||||||
private func emitAckCallback(socket:SocketIOClient, num:Int)
|
private func emitAckCallback(socket:SocketIOClient, num:Int)
|
||||||
// Curried
|
// Curried
|
||||||
(items:AnyObject...) -> Void {
|
(items:AnyObject...) -> Void {
|
||||||
|
|||||||
@ -3,6 +3,7 @@
|
|||||||
// Socket.IO-Swift
|
// Socket.IO-Swift
|
||||||
//
|
//
|
||||||
// Created by Erik Little on 3/16/15.
|
// Created by Erik Little on 3/16/15.
|
||||||
|
//
|
||||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
// of this software and associated documentation files (the "Software"), to deal
|
// of this software and associated documentation files (the "Software"), to deal
|
||||||
// in the Software without restriction, including without limitation the rights
|
// in the Software without restriction, including without limitation the rights
|
||||||
|
|||||||
@ -195,7 +195,7 @@ public class SocketIOClient: NSObject, SocketEngineClient {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
self?.ackHandlers.addAck(ack, callback)
|
self?.ackHandlers.addAck(ack, callback: callback)
|
||||||
|
|
||||||
dispatch_async(self!.emitQueue) {
|
dispatch_async(self!.emitQueue) {
|
||||||
self?._emit(event, items, ack: ack)
|
self?._emit(event, items, ack: ack)
|
||||||
@ -292,7 +292,7 @@ public class SocketIOClient: NSObject, SocketEngineClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let packet = SocketPacket(type: nil, data: args, nsp: self.nsp, id: ack)
|
let packet = SocketPacket(type: nil, data: args, nsp: self.nsp, id: ack)
|
||||||
var str:String
|
let str:String
|
||||||
|
|
||||||
SocketParser.parseForEmit(packet)
|
SocketParser.parseForEmit(packet)
|
||||||
str = packet.createMessageForEvent(event)
|
str = packet.createMessageForEvent(event)
|
||||||
@ -312,7 +312,7 @@ public class SocketIOClient: NSObject, SocketEngineClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let packet = SocketPacket(type: nil, data: args, nsp: self!.nsp, id: ack)
|
let packet = SocketPacket(type: nil, data: args, nsp: self!.nsp, id: ack)
|
||||||
var str:String
|
let str:String
|
||||||
|
|
||||||
SocketParser.parseForEmit(packet)
|
SocketParser.parseForEmit(packet)
|
||||||
str = packet.createAck()
|
str = packet.createAck()
|
||||||
@ -349,7 +349,7 @@ public class SocketIOClient: NSObject, SocketEngineClient {
|
|||||||
var ackData:[AnyObject]?
|
var ackData:[AnyObject]?
|
||||||
|
|
||||||
if data is NSArray {
|
if data is NSArray {
|
||||||
ackData = data as? NSArray
|
ackData = (data as? [AnyObject]?)!
|
||||||
} else if data != nil {
|
} else if data != nil {
|
||||||
ackData = [data!]
|
ackData = [data!]
|
||||||
}
|
}
|
||||||
|
|||||||
@ -24,24 +24,6 @@
|
|||||||
|
|
||||||
import Foundation
|
import Foundation
|
||||||
|
|
||||||
enum SocketPacketType:Int {
|
|
||||||
case CONNECT = 0
|
|
||||||
case DISCONNECT = 1
|
|
||||||
case EVENT = 2
|
|
||||||
case ACK = 3
|
|
||||||
case ERROR = 4
|
|
||||||
case BINARY_EVENT = 5
|
|
||||||
case BINARY_ACK = 6
|
|
||||||
|
|
||||||
init(str:String) {
|
|
||||||
if let int = str.toInt() {
|
|
||||||
self = SocketPacketType(rawValue: int)!
|
|
||||||
} else {
|
|
||||||
self = SocketPacketType(rawValue: 4)!
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class SocketPacket {
|
class SocketPacket {
|
||||||
var binary = ContiguousArray<NSData>()
|
var binary = ContiguousArray<NSData>()
|
||||||
var currentPlace = 0
|
var currentPlace = 0
|
||||||
@ -62,7 +44,7 @@ class SocketPacket {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func getEvent() -> String {
|
func getEvent() -> String {
|
||||||
return data?.removeAtIndex(0) as String
|
return data?.removeAtIndex(0) as! String
|
||||||
}
|
}
|
||||||
|
|
||||||
func addData(data:NSData) -> Bool {
|
func addData(data:NSData) -> Bool {
|
||||||
@ -90,7 +72,7 @@ class SocketPacket {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func createMessageForEvent(event:String) -> String {
|
func createMessageForEvent(event:String) -> String {
|
||||||
var message:String
|
let message:String
|
||||||
var jsonSendError:NSError?
|
var jsonSendError:NSError?
|
||||||
|
|
||||||
if self.binary.count == 0 {
|
if self.binary.count == 0 {
|
||||||
@ -164,7 +146,6 @@ class SocketPacket {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for arg in self.data! {
|
for arg in self.data! {
|
||||||
|
|
||||||
if arg is NSDictionary || arg is [AnyObject] {
|
if arg is NSDictionary || arg is [AnyObject] {
|
||||||
let jsonSend = NSJSONSerialization.dataWithJSONObject(arg,
|
let jsonSend = NSJSONSerialization.dataWithJSONObject(arg,
|
||||||
options: NSJSONWritingOptions(0), error: &err)
|
options: NSJSONWritingOptions(0), error: &err)
|
||||||
@ -205,7 +186,7 @@ class SocketPacket {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
self.data = newArr
|
self.data = newArr as [AnyObject]
|
||||||
}
|
}
|
||||||
|
|
||||||
private func _fillInPlaceholders(data:AnyObject) -> AnyObject {
|
private func _fillInPlaceholders(data:AnyObject) -> AnyObject {
|
||||||
@ -219,7 +200,7 @@ class SocketPacket {
|
|||||||
var newDict = NSMutableDictionary(dictionary: dict)
|
var newDict = NSMutableDictionary(dictionary: dict)
|
||||||
|
|
||||||
for (key, value) in dict {
|
for (key, value) in dict {
|
||||||
newDict[key as NSCopying] = _fillInPlaceholders(value)
|
newDict[key as! NSCopying] = _fillInPlaceholders(value)
|
||||||
}
|
}
|
||||||
|
|
||||||
return newDict
|
return newDict
|
||||||
|
|||||||
@ -22,9 +22,9 @@
|
|||||||
|
|
||||||
import Foundation
|
import Foundation
|
||||||
|
|
||||||
private let shredder = SocketParser.PacketShredder()
|
|
||||||
|
|
||||||
class SocketParser {
|
class SocketParser {
|
||||||
|
private static let shredder = SocketParser.PacketShredder()
|
||||||
|
|
||||||
// Translation of socket.io-parser#deconstructPacket
|
// Translation of socket.io-parser#deconstructPacket
|
||||||
private class PacketShredder {
|
private class PacketShredder {
|
||||||
var buf = ContiguousArray<NSData>()
|
var buf = ContiguousArray<NSData>()
|
||||||
@ -48,7 +48,7 @@ class SocketParser {
|
|||||||
var newDict = NSMutableDictionary(dictionary: dict)
|
var newDict = NSMutableDictionary(dictionary: dict)
|
||||||
|
|
||||||
for (key, value) in newDict {
|
for (key, value) in newDict {
|
||||||
newDict[key as NSCopying] = shred(value)
|
newDict[key as! NSCopying] = shred(value)
|
||||||
}
|
}
|
||||||
|
|
||||||
return newDict
|
return newDict
|
||||||
@ -148,7 +148,7 @@ class SocketParser {
|
|||||||
let d = String(arr[++i...arr.count-1])
|
let d = String(arr[++i...arr.count-1])
|
||||||
let noPlaceholders = d["(\\{\"_placeholder\":true,\"num\":(\\d*)\\})"] ~= "\"~~$2\""
|
let noPlaceholders = d["(\\{\"_placeholder\":true,\"num\":(\\d*)\\})"] ~= "\"~~$2\""
|
||||||
|
|
||||||
let data = SocketParser.parseData(noPlaceholders) as [AnyObject]
|
let data = SocketParser.parseData(noPlaceholders) as! [AnyObject]
|
||||||
|
|
||||||
return SocketPacket(type: SocketPacketType(str: type), data: data,
|
return SocketPacket(type: SocketPacketType(str: type), data: data,
|
||||||
nsp: nsp, placeholders: placeholders, id: id)
|
nsp: nsp, placeholders: placeholders, id: id)
|
||||||
|
|||||||
52
SwiftIO/SocketTypes.swift
Normal file
52
SwiftIO/SocketTypes.swift
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
//
|
||||||
|
// SocketTypes.swift
|
||||||
|
// SocketIO-Swift
|
||||||
|
//
|
||||||
|
// Created by Erik Little on 4/8/15.
|
||||||
|
//
|
||||||
|
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
// of this software and associated documentation files (the "Software"), to deal
|
||||||
|
// in the Software without restriction, including without limitation the rights
|
||||||
|
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
// copies of the Software, and to permit persons to whom the Software is
|
||||||
|
// furnished to do so, subject to the following conditions:
|
||||||
|
//
|
||||||
|
// The above copyright notice and this permission notice shall be included in
|
||||||
|
// all copies or substantial portions of the Software.
|
||||||
|
//
|
||||||
|
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
|
// THE SOFTWARE.
|
||||||
|
|
||||||
|
import Foundation
|
||||||
|
|
||||||
|
// @objc_block is undocumented, but is used because Swift assumes that all
|
||||||
|
// Objective-C blocks are copied, but Objective-C assumes that Swift will copy it.
|
||||||
|
// And the way things are done here, the bridging fails to copy the block in
|
||||||
|
// SocketAckMap#addAck
|
||||||
|
public typealias AckCallback = @objc_block (NSArray?) -> Void
|
||||||
|
public typealias AckEmitter = (AnyObject...) -> Void
|
||||||
|
public typealias NormalCallback = (NSArray?, AckEmitter?) -> Void
|
||||||
|
public typealias OnAckCallback = (timeout:UInt64, callback:AckCallback) -> Void
|
||||||
|
|
||||||
|
enum SocketPacketType:Int {
|
||||||
|
case CONNECT = 0
|
||||||
|
case DISCONNECT = 1
|
||||||
|
case EVENT = 2
|
||||||
|
case ACK = 3
|
||||||
|
case ERROR = 4
|
||||||
|
case BINARY_EVENT = 5
|
||||||
|
case BINARY_ACK = 6
|
||||||
|
|
||||||
|
init(str:String) {
|
||||||
|
if let int = str.toInt() {
|
||||||
|
self = SocketPacketType(rawValue: int)!
|
||||||
|
} else {
|
||||||
|
self = SocketPacketType(rawValue: 4)!
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -43,7 +43,7 @@ public class SwiftRegex: NSObject, BooleanType {
|
|||||||
}
|
}
|
||||||
|
|
||||||
final var targetRange: NSRange {
|
final var targetRange: NSRange {
|
||||||
return NSRange(location: 0,length: countElements(target.utf16))
|
return NSRange(location: 0,length: count(target.utf16))
|
||||||
}
|
}
|
||||||
|
|
||||||
final func substring(range: NSRange) -> String? {
|
final func substring(range: NSRange) -> String? {
|
||||||
@ -138,7 +138,7 @@ public class SwiftRegex: NSObject, BooleanType {
|
|||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
func substituteMatches(substitution: (NSTextCheckingResult, UnsafeMutablePointer<ObjCBool>) -> String,
|
func substituteMatches(substitution: ((NSTextCheckingResult, UnsafeMutablePointer<ObjCBool>) -> String),
|
||||||
options:NSMatchingOptions = nil) -> String {
|
options:NSMatchingOptions = nil) -> String {
|
||||||
let out = NSMutableString()
|
let out = NSMutableString()
|
||||||
var pos = 0
|
var pos = 0
|
||||||
|
|||||||
@ -7,7 +7,6 @@
|
|||||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||||
|
|
||||||
import Foundation
|
import Foundation
|
||||||
import CoreFoundation
|
|
||||||
|
|
||||||
public protocol WebSocketDelegate: class {
|
public protocol WebSocketDelegate: class {
|
||||||
func websocketDidConnect(socket: WebSocket)
|
func websocketDidConnect(socket: WebSocket)
|
||||||
@ -236,8 +235,8 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
}
|
}
|
||||||
if self.selfSignedSSL {
|
if self.selfSignedSSL {
|
||||||
let settings: Dictionary<NSObject, NSObject> = [kCFStreamSSLValidatesCertificateChain: NSNumber(bool:false), kCFStreamSSLPeerName: kCFNull]
|
let settings: Dictionary<NSObject, NSObject> = [kCFStreamSSLValidatesCertificateChain: NSNumber(bool:false), kCFStreamSSLPeerName: kCFNull]
|
||||||
inputStream!.setProperty(settings, forKey: kCFStreamPropertySSLSettings)
|
inputStream!.setProperty(settings, forKey: kCFStreamPropertySSLSettings as String)
|
||||||
outputStream!.setProperty(settings, forKey: kCFStreamPropertySSLSettings)
|
outputStream!.setProperty(settings, forKey: kCFStreamPropertySSLSettings as String)
|
||||||
}
|
}
|
||||||
isRunLoop = true
|
isRunLoop = true
|
||||||
inputStream!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
|
inputStream!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
|
||||||
@ -247,18 +246,18 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
let bytes = UnsafePointer<UInt8>(data.bytes)
|
let bytes = UnsafePointer<UInt8>(data.bytes)
|
||||||
outputStream!.write(bytes, maxLength: data.length)
|
outputStream!.write(bytes, maxLength: data.length)
|
||||||
while(isRunLoop) {
|
while(isRunLoop) {
|
||||||
NSRunLoop.currentRunLoop().runMode(NSDefaultRunLoopMode, beforeDate: NSDate.distantFuture() as NSDate)
|
NSRunLoop.currentRunLoop().runMode(NSDefaultRunLoopMode, beforeDate: NSDate.distantFuture() as! NSDate)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//delegate for the stream methods. Processes incoming bytes
|
//delegate for the stream methods. Processes incoming bytes
|
||||||
func stream(aStream: NSStream!, handleEvent eventCode: NSStreamEvent) {
|
public func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent) {
|
||||||
|
|
||||||
if eventCode == .HasBytesAvailable {
|
if eventCode == .HasBytesAvailable {
|
||||||
if(aStream == inputStream) {
|
if(aStream == inputStream) {
|
||||||
processInputStream()
|
processInputStream()
|
||||||
}
|
}
|
||||||
} else if eventCode == .ErrorOccurred {
|
} else if eventCode == .ErrorOccurred {
|
||||||
disconnectStream(aStream!.streamError)
|
disconnectStream(aStream.streamError)
|
||||||
} else if eventCode == .EndEncountered {
|
} else if eventCode == .EndEncountered {
|
||||||
disconnectStream(nil)
|
disconnectStream(nil)
|
||||||
}
|
}
|
||||||
@ -333,7 +332,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
}
|
}
|
||||||
///Finds the HTTP Packet in the TCP stream, by looking for the CRLF.
|
///Finds the HTTP Packet in the TCP stream, by looking for the CRLF.
|
||||||
private func processHTTP(buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Bool {
|
private func processHTTP(buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Bool {
|
||||||
let CRLFBytes = [UInt8("\r"), UInt8("\n"), UInt8("\r"), UInt8("\n")]
|
let CRLFBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")]
|
||||||
var k = 0
|
var k = 0
|
||||||
var totalSize = 0
|
var totalSize = 0
|
||||||
for var i = 0; i < bufferLen; i++ {
|
for var i = 0; i < bufferLen; i++ {
|
||||||
@ -376,7 +375,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
}
|
}
|
||||||
let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response.takeUnretainedValue())
|
let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response.takeUnretainedValue())
|
||||||
let headers: NSDictionary = cfHeaders.takeUnretainedValue()
|
let headers: NSDictionary = cfHeaders.takeUnretainedValue()
|
||||||
let acceptKey = headers[headerWSAcceptName] as NSString
|
let acceptKey = headers[headerWSAcceptName] as! NSString
|
||||||
if acceptKey.length > 0 {
|
if acceptKey.length > 0 {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
@ -500,7 +499,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
data = NSData(bytes: UnsafePointer<UInt8>((buffer+offset)), length: Int(len))
|
data = NSData(bytes: UnsafePointer<UInt8>((buffer+offset)), length: Int(len))
|
||||||
}
|
}
|
||||||
if receivedOpcode == OpCode.Pong.rawValue {
|
if receivedOpcode == OpCode.Pong.rawValue {
|
||||||
let step = Int(offset+len)
|
let step = offset + Int(len)
|
||||||
let extra = bufferLen-step
|
let extra = bufferLen-step
|
||||||
if extra > 0 {
|
if extra > 0 {
|
||||||
processRawMessage((buffer+step), bufferLen: extra)
|
processRawMessage((buffer+step), bufferLen: extra)
|
||||||
@ -565,7 +564,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
processResponse(response!)
|
processResponse(response!)
|
||||||
}
|
}
|
||||||
|
|
||||||
let step = Int(offset+len)
|
let step = offset + Int(len)
|
||||||
let extra = bufferLen-step
|
let extra = bufferLen-step
|
||||||
if(extra > 0) {
|
if(extra > 0) {
|
||||||
processExtra((buffer+step), bufferLen: extra)
|
processExtra((buffer+step), bufferLen: extra)
|
||||||
@ -597,9 +596,9 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
}
|
}
|
||||||
dispatch_async(queue,{
|
dispatch_async(queue,{
|
||||||
if let textBlock = self.receivedTextBlock{
|
if let textBlock = self.receivedTextBlock{
|
||||||
textBlock(str!)
|
textBlock(str! as String)
|
||||||
}
|
}
|
||||||
self.delegate?.websocketDidReceiveMessage(self, text: str!)
|
self.delegate?.websocketDidReceiveMessage(self, text: str! as String)
|
||||||
})
|
})
|
||||||
} else if response.code == .BinaryFrame {
|
} else if response.code == .BinaryFrame {
|
||||||
let data = response.buffer! //local copy so it is perverse for writing
|
let data = response.buffer! //local copy so it is perverse for writing
|
||||||
@ -673,7 +672,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
}
|
}
|
||||||
buffer[1] |= self.MaskMask
|
buffer[1] |= self.MaskMask
|
||||||
var maskKey = UnsafeMutablePointer<UInt8>(buffer + offset)
|
var maskKey = UnsafeMutablePointer<UInt8>(buffer + offset)
|
||||||
SecRandomCopyBytes(kSecRandomDefault, UInt(sizeof(UInt32)), maskKey)
|
SecRandomCopyBytes(kSecRandomDefault, Int(sizeof(UInt32)), maskKey)
|
||||||
offset += sizeof(UInt32)
|
offset += sizeof(UInt32)
|
||||||
|
|
||||||
for (var i = 0; i < dataLength; i++) {
|
for (var i = 0; i < dataLength; i++) {
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user