untested with socket.io, this just compiles
This commit is contained in:
parent
58571e5387
commit
78727dc0ee
@ -88,7 +88,7 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
|
|||||||
case NOOP = 6
|
case NOOP = 6
|
||||||
|
|
||||||
init?(str:String?) {
|
init?(str:String?) {
|
||||||
if let value = str?.toInt(), raw = PacketType(rawValue: value) {
|
if let value = Int(str ?? ""), raw = PacketType(rawValue: value) {
|
||||||
self = raw
|
self = raw
|
||||||
} else {
|
} else {
|
||||||
return nil
|
return nil
|
||||||
@ -115,7 +115,7 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
|
|||||||
SocketLogger.log("Engine is being deinit", client: self)
|
SocketLogger.log("Engine is being deinit", client: self)
|
||||||
}
|
}
|
||||||
|
|
||||||
public func close(#fast:Bool) {
|
public func close(fast fast:Bool) {
|
||||||
SocketLogger.log("Engine is being closed. Fast: %@", client: self, args: fast)
|
SocketLogger.log("Engine is being closed. Fast: %@", client: self, args: fast)
|
||||||
|
|
||||||
pingTimer?.invalidate()
|
pingTimer?.invalidate()
|
||||||
@ -135,7 +135,7 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
|
|||||||
if websocket {
|
if websocket {
|
||||||
var byteArray = [UInt8](count: 1, repeatedValue: 0x0)
|
var byteArray = [UInt8](count: 1, repeatedValue: 0x0)
|
||||||
byteArray[0] = 4
|
byteArray[0] = 4
|
||||||
var mutData = NSMutableData(bytes: &byteArray, length: 1)
|
let mutData = NSMutableData(bytes: &byteArray, length: 1)
|
||||||
|
|
||||||
mutData.appendData(data)
|
mutData.appendData(data)
|
||||||
|
|
||||||
@ -156,7 +156,7 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
|
|||||||
|
|
||||||
let path = socketPath == "" ? "/socket.io" : socketPath
|
let path = socketPath == "" ? "/socket.io" : socketPath
|
||||||
|
|
||||||
var url = "\(client!.socketURL)\(path)/?transport="
|
let url = "\(client!.socketURL)\(path)/?transport="
|
||||||
var urlPolling:String
|
var urlPolling:String
|
||||||
var urlWebSocket:String
|
var urlWebSocket:String
|
||||||
|
|
||||||
@ -243,18 +243,18 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
|
|||||||
|
|
||||||
session.dataTaskWithRequest(req) {[weak self] data, res, err in
|
session.dataTaskWithRequest(req) {[weak self] data, res, err in
|
||||||
if let this = self {
|
if let this = self {
|
||||||
if err != nil {
|
if err != nil || data == nil {
|
||||||
if this.polling {
|
if this.polling {
|
||||||
this.handlePollingFailed(err.localizedDescription)
|
this.handlePollingFailed(err?.localizedDescription ?? "Error")
|
||||||
} else {
|
} else {
|
||||||
SocketLogger.err(err.localizedDescription, client: this)
|
SocketLogger.err(err?.localizedDescription ?? "Error", client: this)
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
SocketLogger.log("Got polling response", client: this)
|
SocketLogger.log("Got polling response", client: this)
|
||||||
|
|
||||||
if let str = NSString(data: data, encoding: NSUTF8StringEncoding) as? String {
|
if let str = NSString(data: data!, encoding: NSUTF8StringEncoding) as? String {
|
||||||
dispatch_async(this.parseQueue) {[weak this] in
|
dispatch_async(this.parseQueue) {[weak this] in
|
||||||
this?.parsePollingMessage(str)
|
this?.parsePollingMessage(str)
|
||||||
}
|
}
|
||||||
@ -267,7 +267,7 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
|
|||||||
} else if !this.closed && this.polling {
|
} else if !this.closed && this.polling {
|
||||||
this.doPoll()
|
this.doPoll()
|
||||||
}
|
}
|
||||||
}}.resume()
|
}}?.resume()
|
||||||
}
|
}
|
||||||
|
|
||||||
private func flushProbeWait() {
|
private func flushProbeWait() {
|
||||||
@ -299,7 +299,7 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
|
|||||||
var postStr = ""
|
var postStr = ""
|
||||||
|
|
||||||
for packet in postWait {
|
for packet in postWait {
|
||||||
let len = count(packet)
|
let len = packet.characters.count
|
||||||
|
|
||||||
postStr += "\(len):\(packet)"
|
postStr += "\(len):\(packet)"
|
||||||
}
|
}
|
||||||
@ -329,10 +329,10 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
|
|||||||
session.dataTaskWithRequest(req) {[weak self] data, res, err in
|
session.dataTaskWithRequest(req) {[weak self] data, res, err in
|
||||||
if let this = self {
|
if let this = self {
|
||||||
if err != nil && this.polling {
|
if err != nil && this.polling {
|
||||||
this.handlePollingFailed(err.localizedDescription)
|
this.handlePollingFailed(err?.localizedDescription ?? "Error")
|
||||||
return
|
return
|
||||||
} else if err != nil {
|
} else if err != nil {
|
||||||
NSLog(err.localizedDescription)
|
NSLog(err?.localizedDescription ?? "Error")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -344,7 +344,7 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
|
|||||||
this?.doPoll()
|
this?.doPoll()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}}.resume()
|
}}?.resume()
|
||||||
}
|
}
|
||||||
|
|
||||||
// We had packets waiting for send when we upgraded
|
// We had packets waiting for send when we upgraded
|
||||||
@ -391,12 +391,12 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private func handleOpen(openData:String) {
|
private func handleOpen(openData:String) {
|
||||||
var err:NSError?
|
|
||||||
let mesData = openData.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
|
let mesData = openData.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
|
||||||
|
|
||||||
if let json = NSJSONSerialization.JSONObjectWithData(mesData,
|
do {
|
||||||
options: NSJSONReadingOptions.AllowFragments,
|
let json = try NSJSONSerialization.JSONObjectWithData(mesData,
|
||||||
error: &err) as? NSDictionary, sid = json["sid"] as? String {
|
options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
|
||||||
|
if let sid = json?["sid"] as? String {
|
||||||
self.sid = sid
|
self.sid = sid
|
||||||
_connected = true
|
_connected = true
|
||||||
|
|
||||||
@ -404,13 +404,13 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
|
|||||||
createWebsocket(andConnect: true)
|
createWebsocket(andConnect: true)
|
||||||
}
|
}
|
||||||
|
|
||||||
if let pingInterval = json["pingInterval"] as? Int, pingTimeout = json["pingTimeout"] as? Int {
|
if let pingInterval = json?["pingInterval"] as? Int, pingTimeout = json?["pingTimeout"] as? Int {
|
||||||
self.pingInterval = pingInterval / 1000
|
self.pingInterval = pingInterval / 1000
|
||||||
self.pingTimeout = pingTimeout / 1000
|
self.pingTimeout = pingTimeout / 1000
|
||||||
}
|
}
|
||||||
} else {
|
}
|
||||||
client?.didError("Engine failed to handshake")
|
} catch {
|
||||||
return
|
SocketLogger.err("Error parsing open packet", client: self)
|
||||||
}
|
}
|
||||||
|
|
||||||
startPingTimer()
|
startPingTimer()
|
||||||
@ -482,19 +482,19 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
|
|||||||
|
|
||||||
// Translatation of engine.io-parser#decodePayload
|
// Translatation of engine.io-parser#decodePayload
|
||||||
private func parsePollingMessage(str:String) {
|
private func parsePollingMessage(str:String) {
|
||||||
if count(str) == 1 {
|
if str.characters.count == 1 {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// println(str)
|
// println(str)
|
||||||
|
|
||||||
let strArray = Array(str)
|
let strArray = Array(str.characters)
|
||||||
var length = ""
|
var length = ""
|
||||||
var n = 0
|
var n = 0
|
||||||
var msg = ""
|
var msg = ""
|
||||||
|
|
||||||
func testLength(length:String, inout n:Int) -> Bool {
|
func testLength(length:String, inout n:Int) -> Bool {
|
||||||
if let num = length.toInt() {
|
if let num = Int(length) {
|
||||||
n = num
|
n = num
|
||||||
return false
|
return false
|
||||||
} else {
|
} else {
|
||||||
@ -502,13 +502,13 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for var i = 0, l = count(str); i < l; i++ {
|
for var i = 0, l = str.characters.count; i < l; i++ {
|
||||||
let chr = String(strArray[i])
|
let chr = String(strArray[i])
|
||||||
|
|
||||||
if chr != ":" {
|
if chr != ":" {
|
||||||
length += chr
|
length += chr
|
||||||
} else {
|
} else {
|
||||||
if length == "" || testLength(length, &n) {
|
if length == "" || testLength(length, n: &n) {
|
||||||
SocketLogger.err("Parsing error: %@", client: self, args: str)
|
SocketLogger.err("Parsing error: %@", client: self, args: str)
|
||||||
handlePollingFailed("Error parsing XHR message")
|
handlePollingFailed("Error parsing XHR message")
|
||||||
return
|
return
|
||||||
@ -516,12 +516,12 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
|
|||||||
|
|
||||||
msg = String(strArray[i+1...i+n])
|
msg = String(strArray[i+1...i+n])
|
||||||
|
|
||||||
if let lengthInt = length.toInt() where lengthInt != count(msg) {
|
if let lengthInt = Int(length) where lengthInt != msg.characters.count {
|
||||||
SocketLogger.err("Parsing error: %@", client: self, args: str)
|
SocketLogger.err("Parsing error: %@", client: self, args: str)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if count(msg) != 0 {
|
if msg.characters.count != 0 {
|
||||||
// Be sure to capture the value of the msg
|
// Be sure to capture the value of the msg
|
||||||
dispatch_async(handleQueue) {[weak self, msg] in
|
dispatch_async(handleQueue) {[weak self, msg] in
|
||||||
self?.parseEngineMessage(msg, fromPolling: true)
|
self?.parseEngineMessage(msg, fromPolling: true)
|
||||||
@ -552,7 +552,7 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
|
|||||||
let type = PacketType(str: (message["^(\\d)"].groups()?[1])) ?? {
|
let type = PacketType(str: (message["^(\\d)"].groups()?[1])) ?? {
|
||||||
self.checkIfMessageIsBase64Binary(message)
|
self.checkIfMessageIsBase64Binary(message)
|
||||||
return PacketType.NOOP
|
return PacketType.NOOP
|
||||||
}()
|
}()
|
||||||
|
|
||||||
switch type {
|
switch type {
|
||||||
case PacketType.MESSAGE:
|
case PacketType.MESSAGE:
|
||||||
@ -612,7 +612,7 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
|
|||||||
|
|
||||||
if datas != nil {
|
if datas != nil {
|
||||||
for data in datas! {
|
for data in datas! {
|
||||||
let (nilData, b64Data) = createBinaryDataForSend(data)
|
let (_, b64Data) = createBinaryDataForSend(data)
|
||||||
|
|
||||||
postWait.append(b64Data!)
|
postWait.append(b64Data!)
|
||||||
}
|
}
|
||||||
@ -633,7 +633,7 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
|
|||||||
|
|
||||||
if datas != nil {
|
if datas != nil {
|
||||||
for data in datas! {
|
for data in datas! {
|
||||||
let (data, nilString) = createBinaryDataForSend(data)
|
let (data, _) = createBinaryDataForSend(data)
|
||||||
if data != nil {
|
if data != nil {
|
||||||
ws?.writeData(data!)
|
ws?.writeData(data!)
|
||||||
}
|
}
|
||||||
|
|||||||
@ -24,24 +24,24 @@
|
|||||||
|
|
||||||
import Foundation
|
import Foundation
|
||||||
|
|
||||||
private func emitAckCallback(socket:SocketIOClient, num:Int)
|
private func emitAckCallback(socket:SocketIOClient?, num:Int?)
|
||||||
(items:AnyObject...) -> Void {
|
(items:[AnyObject]) -> Void {
|
||||||
socket.emitAck(num, withData: items)
|
socket?.emitAck(num ?? -1, withData: items)
|
||||||
}
|
}
|
||||||
|
|
||||||
final class SocketEventHandler {
|
final class SocketEventHandler {
|
||||||
let event:String!
|
let event:String!
|
||||||
let callback:NormalCallback?
|
let callback:NormalCallback
|
||||||
|
|
||||||
init(event:String, callback:NormalCallback) {
|
init(event:String, callback:NormalCallback) {
|
||||||
self.event = event
|
self.event = event
|
||||||
self.callback = callback
|
self.callback = callback
|
||||||
}
|
}
|
||||||
|
|
||||||
func executeCallback(_ items:NSArray? = nil, withAck ack:Int? = nil, withAckType type:Int? = nil,
|
func executeCallback(items:NSArray? = nil, withAck ack:Int? = nil, withAckType type:Int? = nil,
|
||||||
withSocket socket:SocketIOClient? = nil) {
|
withSocket socket:SocketIOClient? = nil) {
|
||||||
dispatch_async(dispatch_get_main_queue()) {[weak self] in
|
dispatch_async(dispatch_get_main_queue()) {[weak self] in
|
||||||
self?.callback?(items, ack != nil ? emitAckCallback(socket!, ack!) : nil)
|
self?.callback(items, emitAckCallback(socket, num: ack))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -145,7 +145,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketLogClient
|
|||||||
Will turn off automatic reconnects.
|
Will turn off automatic reconnects.
|
||||||
Pass true to fast if you're closing from a background task
|
Pass true to fast if you're closing from a background task
|
||||||
*/
|
*/
|
||||||
public func close(#fast:Bool) {
|
public func close(fast fast:Bool) {
|
||||||
SocketLogger.log("Closing socket", client: self)
|
SocketLogger.log("Closing socket", client: self)
|
||||||
|
|
||||||
reconnects = false
|
reconnects = false
|
||||||
@ -166,7 +166,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketLogClient
|
|||||||
/**
|
/**
|
||||||
Connect to the server. If we aren't connected after timeoutAfter, call handler
|
Connect to the server. If we aren't connected after timeoutAfter, call handler
|
||||||
*/
|
*/
|
||||||
public func connect(#timeoutAfter:Int, withTimeoutHandler handler:(() -> Void)?) {
|
public func connect(timeoutAfter timeoutAfter:Int, withTimeoutHandler handler:(() -> Void)?) {
|
||||||
if closed {
|
if closed {
|
||||||
SocketLogger.log("Warning! This socket was previously closed. This might be dangerous!", client: self)
|
SocketLogger.log("Warning! This socket was previously closed. This might be dangerous!", client: self)
|
||||||
_closed = false
|
_closed = false
|
||||||
@ -175,7 +175,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketLogClient
|
|||||||
}
|
}
|
||||||
|
|
||||||
addEngine()
|
addEngine()
|
||||||
engine?.open(opts: connectParams)
|
engine?.open(connectParams)
|
||||||
|
|
||||||
if timeoutAfter == 0 {
|
if timeoutAfter == 0 {
|
||||||
return
|
return
|
||||||
@ -260,7 +260,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketLogClient
|
|||||||
/**
|
/**
|
||||||
Same as close
|
Same as close
|
||||||
*/
|
*/
|
||||||
public func disconnect(#fast:Bool) {
|
public func disconnect(fast fast:Bool) {
|
||||||
close(fast: fast)
|
close(fast: fast)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -433,7 +433,7 @@ public final class SocketIOClient: NSObject, SocketEngineClient, SocketLogClient
|
|||||||
public func off(event:String) {
|
public func off(event:String) {
|
||||||
SocketLogger.log("Removing handler for event: %@", client: self, args: event)
|
SocketLogger.log("Removing handler for event: %@", client: self, args: event)
|
||||||
|
|
||||||
handlers = handlers.filter {$0.event == event ? false : true}
|
handlers = ContiguousArray(handlers.filter {$0.event == event ? false : true})
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@ -24,8 +24,6 @@
|
|||||||
|
|
||||||
import Foundation
|
import Foundation
|
||||||
|
|
||||||
private let MESSAGE_LENGTH_MAX = 10000
|
|
||||||
|
|
||||||
protocol SocketLogClient {
|
protocol SocketLogClient {
|
||||||
var log:Bool {get set}
|
var log:Bool {get set}
|
||||||
var logType:String {get}
|
var logType:String {get}
|
||||||
@ -34,16 +32,8 @@ protocol SocketLogClient {
|
|||||||
final class SocketLogger {
|
final class SocketLogger {
|
||||||
private static let printQueue = dispatch_queue_create("printQueue", DISPATCH_QUEUE_SERIAL)
|
private static let printQueue = dispatch_queue_create("printQueue", DISPATCH_QUEUE_SERIAL)
|
||||||
|
|
||||||
private static func shorten(item:AnyObject) -> CVarArgType {
|
private static func toCVArgType(item:AnyObject) -> CVarArgType {
|
||||||
var str = toString(item)
|
return String(item)
|
||||||
|
|
||||||
if count(str) > MESSAGE_LENGTH_MAX {
|
|
||||||
let endIndex = advance(str.startIndex, MESSAGE_LENGTH_MAX)
|
|
||||||
|
|
||||||
str = str.substringToIndex(endIndex)
|
|
||||||
}
|
|
||||||
|
|
||||||
return str
|
|
||||||
}
|
}
|
||||||
|
|
||||||
static func log(message:String, client:SocketLogClient, altType:String? = nil, args:AnyObject...) {
|
static func log(message:String, client:SocketLogClient, altType:String? = nil, args:AnyObject...) {
|
||||||
@ -52,7 +42,7 @@ final class SocketLogger {
|
|||||||
}
|
}
|
||||||
|
|
||||||
dispatch_async(printQueue) {[type = client.logType] in
|
dispatch_async(printQueue) {[type = client.logType] in
|
||||||
let newArgs = args.map(SocketLogger.shorten)
|
let newArgs = args.map(SocketLogger.toCVArgType)
|
||||||
let replaced = String(format: message, arguments: newArgs)
|
let replaced = String(format: message, arguments: newArgs)
|
||||||
|
|
||||||
NSLog("%@: %@", altType ?? type, replaced)
|
NSLog("%@: %@", altType ?? type, replaced)
|
||||||
@ -65,7 +55,7 @@ final class SocketLogger {
|
|||||||
}
|
}
|
||||||
|
|
||||||
dispatch_async(printQueue) {[type = client.logType] in
|
dispatch_async(printQueue) {[type = client.logType] in
|
||||||
let newArgs = args.map(SocketLogger.shorten)
|
let newArgs = args.map(SocketLogger.toCVArgType)
|
||||||
let replaced = String(format: message, arguments: newArgs)
|
let replaced = String(format: message, arguments: newArgs)
|
||||||
|
|
||||||
NSLog("ERROR %@: %@", altType ?? type, replaced)
|
NSLog("ERROR %@: %@", altType ?? type, replaced)
|
||||||
|
|||||||
@ -24,7 +24,7 @@
|
|||||||
|
|
||||||
import Foundation
|
import Foundation
|
||||||
|
|
||||||
final class SocketPacket: Printable {
|
final class SocketPacket: CustomStringConvertible {
|
||||||
var binary = ContiguousArray<NSData>()
|
var binary = ContiguousArray<NSData>()
|
||||||
var currentPlace = 0
|
var currentPlace = 0
|
||||||
var data:[AnyObject]?
|
var data:[AnyObject]?
|
||||||
@ -55,7 +55,7 @@ final class SocketPacket: Printable {
|
|||||||
case BINARY_ACK = 6
|
case BINARY_ACK = 6
|
||||||
|
|
||||||
init?(str:String) {
|
init?(str:String) {
|
||||||
if let int = str.toInt(), raw = PacketType(rawValue: int) {
|
if let int = Int(str), raw = PacketType(rawValue: int) {
|
||||||
self = raw
|
self = raw
|
||||||
} else {
|
} else {
|
||||||
return nil
|
return nil
|
||||||
@ -167,8 +167,14 @@ final class SocketPacket: Printable {
|
|||||||
|
|
||||||
for arg in data! {
|
for arg in data! {
|
||||||
if arg is NSDictionary || arg is [AnyObject] {
|
if arg is NSDictionary || arg is [AnyObject] {
|
||||||
let jsonSend = NSJSONSerialization.dataWithJSONObject(arg,
|
let jsonSend: NSData?
|
||||||
options: NSJSONWritingOptions(0), error: &err)
|
do {
|
||||||
|
jsonSend = try NSJSONSerialization.dataWithJSONObject(arg,
|
||||||
|
options: NSJSONWritingOptions(rawValue: 0))
|
||||||
|
} catch var error as NSError {
|
||||||
|
err = error
|
||||||
|
jsonSend = nil
|
||||||
|
}
|
||||||
let jsonString = NSString(data: jsonSend!, encoding: NSUTF8StringEncoding)
|
let jsonString = NSString(data: jsonSend!, encoding: NSUTF8StringEncoding)
|
||||||
|
|
||||||
message += jsonString! as String + ","
|
message += jsonString! as String + ","
|
||||||
@ -192,11 +198,11 @@ final class SocketPacket: Printable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func fillInPlaceholders() {
|
func fillInPlaceholders() {
|
||||||
var newArr = NSMutableArray(array: data!)
|
let newArr = NSMutableArray(array: data!)
|
||||||
|
|
||||||
for i in 0..<data!.count {
|
for i in 0..<data!.count {
|
||||||
if let str = data?[i] as? String, num = str["~~(\\d)"].groups() {
|
if let str = data?[i] as? String, num = str["~~(\\d)"].groups() {
|
||||||
newArr[i] = binary[num[1].toInt()!]
|
newArr[i] = binary[Int(num[1])!]
|
||||||
} else if data?[i] is NSDictionary || data?[i] is NSArray {
|
} else if data?[i] is NSDictionary || data?[i] is NSArray {
|
||||||
newArr[i] = _fillInPlaceholders(data![i])
|
newArr[i] = _fillInPlaceholders(data![i])
|
||||||
}
|
}
|
||||||
@ -208,12 +214,12 @@ final class SocketPacket: Printable {
|
|||||||
private func _fillInPlaceholders(data:AnyObject) -> AnyObject {
|
private func _fillInPlaceholders(data:AnyObject) -> AnyObject {
|
||||||
if let str = data as? String {
|
if let str = data as? String {
|
||||||
if let num = str["~~(\\d)"].groups() {
|
if let num = str["~~(\\d)"].groups() {
|
||||||
return binary[num[1].toInt()!]
|
return binary[Int(num[1])!]
|
||||||
} else {
|
} else {
|
||||||
return str
|
return str
|
||||||
}
|
}
|
||||||
} else if let dict = data as? NSDictionary {
|
} else if let dict = data as? NSDictionary {
|
||||||
var newDict = NSMutableDictionary(dictionary: dict)
|
let 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)
|
||||||
@ -221,7 +227,7 @@ final class SocketPacket: Printable {
|
|||||||
|
|
||||||
return newDict
|
return newDict
|
||||||
} else if let arr = data as? NSArray {
|
} else if let arr = data as? NSArray {
|
||||||
var newArr = NSMutableArray(array: arr)
|
let newArr = NSMutableArray(array: arr)
|
||||||
|
|
||||||
for i in 0..<arr.count {
|
for i in 0..<arr.count {
|
||||||
newArr[i] = _fillInPlaceholders(arr[i])
|
newArr[i] = _fillInPlaceholders(arr[i])
|
||||||
|
|||||||
@ -37,7 +37,7 @@ class SocketParser {
|
|||||||
|
|
||||||
return placeholder
|
return placeholder
|
||||||
} else if let arr = data as? NSArray {
|
} else if let arr = data as? NSArray {
|
||||||
var newArr = NSMutableArray(array: arr)
|
let newArr = NSMutableArray(array: arr)
|
||||||
|
|
||||||
for i in 0..<arr.count {
|
for i in 0..<arr.count {
|
||||||
newArr[i] = shred(arr[i])
|
newArr[i] = shred(arr[i])
|
||||||
@ -45,7 +45,7 @@ class SocketParser {
|
|||||||
|
|
||||||
return newArr
|
return newArr
|
||||||
} else if let dict = data as? NSDictionary {
|
} else if let dict = data as? NSDictionary {
|
||||||
var newDict = NSMutableDictionary(dictionary: dict)
|
let 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)
|
||||||
@ -81,7 +81,7 @@ class SocketParser {
|
|||||||
|
|
||||||
// Translation of socket.io-client#decodeString
|
// Translation of socket.io-client#decodeString
|
||||||
static func parseString(str:String) -> SocketPacket? {
|
static func parseString(str:String) -> SocketPacket? {
|
||||||
let arr = Array(str)
|
let arr = Array(str.characters)
|
||||||
let type = String(arr[0])
|
let type = String(arr[0])
|
||||||
|
|
||||||
if arr.count == 1 {
|
if arr.count == 1 {
|
||||||
@ -103,7 +103,7 @@ class SocketParser {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if let holders = buf.toInt() where arr[i] == "-" {
|
if let holders = Int(buf) where arr[i] == "-" {
|
||||||
placeholders = holders
|
placeholders = holders
|
||||||
} else {
|
} else {
|
||||||
NSLog("Error parsing \(str)")
|
NSLog("Error parsing \(str)")
|
||||||
@ -130,10 +130,10 @@ class SocketParser {
|
|||||||
|
|
||||||
let next = String(arr[i + 1])
|
let next = String(arr[i + 1])
|
||||||
|
|
||||||
if next.toInt() != nil {
|
if Int(next) != nil {
|
||||||
var c = ""
|
var c = ""
|
||||||
while ++i < arr.count {
|
while ++i < arr.count {
|
||||||
if let int = String(arr[i]).toInt() {
|
if let int = Int(String(arr[i])) {
|
||||||
c += String(arr[i])
|
c += String(arr[i])
|
||||||
} else {
|
} else {
|
||||||
--i
|
--i
|
||||||
@ -141,11 +141,11 @@ class SocketParser {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
id = c.toInt()
|
id = Int(c)
|
||||||
}
|
}
|
||||||
|
|
||||||
if ++i < arr.count {
|
if ++i < arr.count {
|
||||||
let d = str[advance(str.startIndex, i)...advance(str.startIndex, count(str)-1)]
|
let d = str[advance(str.startIndex, i)...advance(str.startIndex, str.characters.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] ?? [noPlaceholders]
|
let data = SocketParser.parseData(noPlaceholders) as? [AnyObject] ?? [noPlaceholders]
|
||||||
|
|
||||||
@ -160,8 +160,14 @@ class SocketParser {
|
|||||||
static func parseData(data:String) -> AnyObject? {
|
static func parseData(data:String) -> AnyObject? {
|
||||||
var err:NSError?
|
var err:NSError?
|
||||||
let stringData = data.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
|
let stringData = data.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
|
||||||
let parsed:AnyObject? = NSJSONSerialization.JSONObjectWithData(stringData!,
|
let parsed:AnyObject?
|
||||||
options: NSJSONReadingOptions.MutableContainers, error: &err)
|
do {
|
||||||
|
parsed = try NSJSONSerialization.JSONObjectWithData(stringData!,
|
||||||
|
options: NSJSONReadingOptions.MutableContainers)
|
||||||
|
} catch var error as NSError {
|
||||||
|
err = error
|
||||||
|
parsed = nil
|
||||||
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// println(err)
|
// println(err)
|
||||||
|
|||||||
@ -28,7 +28,7 @@ import Foundation
|
|||||||
// Objective-C blocks are copied, but Objective-C assumes that Swift will copy it.
|
// 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
|
// And the way things are done here, the bridging fails to copy the block in
|
||||||
// SocketAckMap#addAck
|
// SocketAckMap#addAck
|
||||||
public typealias AckCallback = @objc_block (NSArray?) -> Void
|
public typealias AckCallback = @convention(block) (NSArray?) -> Void
|
||||||
public typealias AckEmitter = (AnyObject...) -> Void
|
public typealias AckEmitter = ([AnyObject]) -> Void
|
||||||
public typealias NormalCallback = (NSArray?, AckEmitter?) -> Void
|
public typealias NormalCallback = (NSArray?, AckEmitter?) -> Void
|
||||||
public typealias OnAckCallback = (timeout:UInt64, callback:AckCallback) -> Void
|
public typealias OnAckCallback = (timeout:UInt64, callback:AckCallback) -> Void
|
||||||
|
|||||||
@ -19,17 +19,19 @@ public class SwiftRegex: NSObject, BooleanType {
|
|||||||
var target:String
|
var target:String
|
||||||
var regex: NSRegularExpression
|
var regex: NSRegularExpression
|
||||||
|
|
||||||
init(target:String, pattern:String, options:NSRegularExpressionOptions = nil) {
|
init(target:String, pattern:String, options:NSRegularExpressionOptions?) {
|
||||||
self.target = target
|
self.target = target
|
||||||
if let regex = swiftRegexCache[pattern] {
|
if let regex = swiftRegexCache[pattern] {
|
||||||
self.regex = regex
|
self.regex = regex
|
||||||
} else {
|
} else {
|
||||||
var error: NSError?
|
var error: NSError?
|
||||||
if let regex = NSRegularExpression(pattern: pattern, options:options, error:&error) {
|
do {
|
||||||
|
let regex = try NSRegularExpression(pattern: pattern, options:
|
||||||
|
NSRegularExpressionOptions.DotMatchesLineSeparators)
|
||||||
swiftRegexCache[pattern] = regex
|
swiftRegexCache[pattern] = regex
|
||||||
self.regex = regex
|
self.regex = regex
|
||||||
}
|
} catch let error1 as NSError {
|
||||||
else {
|
error = error1
|
||||||
SwiftRegex.failure("Error in pattern: \(pattern) - \(error)")
|
SwiftRegex.failure("Error in pattern: \(pattern) - \(error)")
|
||||||
self.regex = NSRegularExpression()
|
self.regex = NSRegularExpression()
|
||||||
}
|
}
|
||||||
@ -38,12 +40,12 @@ public class SwiftRegex: NSObject, BooleanType {
|
|||||||
}
|
}
|
||||||
|
|
||||||
class func failure(message: String) {
|
class func failure(message: String) {
|
||||||
println("SwiftRegex: "+message)
|
print("SwiftRegex: "+message)
|
||||||
//assert(false,"SwiftRegex: failed")
|
//assert(false,"SwiftRegex: failed")
|
||||||
}
|
}
|
||||||
|
|
||||||
final var targetRange: NSRange {
|
final var targetRange: NSRange {
|
||||||
return NSRange(location: 0,length: count(target.utf16))
|
return NSRange(location: 0,length: target.utf16.count)
|
||||||
}
|
}
|
||||||
|
|
||||||
final func substring(range: NSRange) -> String? {
|
final func substring(range: NSRange) -> String? {
|
||||||
@ -54,20 +56,21 @@ public class SwiftRegex: NSObject, BooleanType {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public func doesMatch(options: NSMatchingOptions = nil) -> Bool {
|
public func doesMatch(options: NSMatchingOptions!) -> Bool {
|
||||||
return range(options: options).location != NSNotFound
|
return range(options).location != NSNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
public func range(options: NSMatchingOptions = nil) -> NSRange {
|
public func range(options: NSMatchingOptions) -> NSRange {
|
||||||
return regex.rangeOfFirstMatchInString(target as String, options: nil, range: targetRange)
|
return regex.rangeOfFirstMatchInString(target as String, options: [], range: targetRange)
|
||||||
}
|
}
|
||||||
|
|
||||||
public func match(options: NSMatchingOptions = nil) -> String? {
|
public func match(options: NSMatchingOptions) -> String? {
|
||||||
return substring(range(options: options))
|
return substring(range(options))
|
||||||
}
|
}
|
||||||
|
|
||||||
public func groups(options: NSMatchingOptions = nil) -> [String]? {
|
public func groups() -> [String]? {
|
||||||
return groupsForMatch(regex.firstMatchInString(target as String, options: options, range: targetRange))
|
return groupsForMatch(regex.firstMatchInString(target as String, options:
|
||||||
|
NSMatchingOptions.WithoutAnchoringBounds, range: targetRange))
|
||||||
}
|
}
|
||||||
|
|
||||||
func groupsForMatch(match: NSTextCheckingResult!) -> [String]? {
|
func groupsForMatch(match: NSTextCheckingResult!) -> [String]? {
|
||||||
@ -96,7 +99,7 @@ public class SwiftRegex: NSObject, BooleanType {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
for match in matchResults()!.reverse() {
|
for match in Array(matchResults().reverse()) {
|
||||||
let replacement = regex.replacementStringForResult(match,
|
let replacement = regex.replacementStringForResult(match,
|
||||||
inString: target as String, offset: 0, template: newValue!)
|
inString: target as String, offset: 0, template: newValue!)
|
||||||
let mut = NSMutableString(string: target)
|
let mut = NSMutableString(string: target)
|
||||||
@ -107,48 +110,43 @@ public class SwiftRegex: NSObject, BooleanType {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func matchResults(options: NSMatchingOptions = nil) -> [NSTextCheckingResult]? {
|
func matchResults() -> [NSTextCheckingResult] {
|
||||||
let matches = regex.matchesInString(target as String, options: options, range: targetRange)
|
let matches = regex.matchesInString(target as String, options:
|
||||||
as? [NSTextCheckingResult]
|
NSMatchingOptions.WithoutAnchoringBounds, range: targetRange)
|
||||||
|
as [NSTextCheckingResult]
|
||||||
|
|
||||||
if matches != nil {
|
return matches
|
||||||
return matches!
|
|
||||||
} else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public func ranges(options: NSMatchingOptions = nil) -> [NSRange] {
|
public func ranges() -> [NSRange] {
|
||||||
return matchResults(options: options)!.map { $0.range }
|
return matchResults().map { $0.range }
|
||||||
}
|
}
|
||||||
|
|
||||||
public func matches(options: NSMatchingOptions = nil) -> [String] {
|
public func matches() -> [String] {
|
||||||
return matchResults(options: options)!.map( { self.substring($0.range)!})
|
return matchResults().map( { self.substring($0.range)!})
|
||||||
}
|
}
|
||||||
|
|
||||||
public func allGroups(options: NSMatchingOptions = nil) -> [[String]?] {
|
public func allGroups() -> [[String]?] {
|
||||||
return matchResults(options: options)!.map {self.groupsForMatch($0)}
|
return matchResults().map {self.groupsForMatch($0)}
|
||||||
}
|
}
|
||||||
|
|
||||||
public func dictionary(options: NSMatchingOptions = nil) -> Dictionary<String,String> {
|
public func dictionary(options: NSMatchingOptions!) -> Dictionary<String,String> {
|
||||||
var out = Dictionary<String,String>()
|
var out = Dictionary<String,String>()
|
||||||
for match in matchResults(options: options)! {
|
for match in matchResults() {
|
||||||
out[substring(match.rangeAtIndex(1))!] = substring(match.rangeAtIndex(2))!
|
out[substring(match.rangeAtIndex(1))!] = substring(match.rangeAtIndex(2))!
|
||||||
}
|
}
|
||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
func substituteMatches(substitution: ((NSTextCheckingResult, UnsafeMutablePointer<ObjCBool>) -> String),
|
func substituteMatches(substitution: ((NSTextCheckingResult, UnsafeMutablePointer<ObjCBool>) -> String),
|
||||||
options:NSMatchingOptions = nil) -> String {
|
options:NSMatchingOptions) -> String {
|
||||||
let out = NSMutableString()
|
let out = NSMutableString()
|
||||||
var pos = 0
|
var pos = 0
|
||||||
|
|
||||||
regex.enumerateMatchesInString(target as String, options: options, range: targetRange ) {
|
regex.enumerateMatchesInString(target as String, options: options, range: targetRange ) {match, flags, stop in
|
||||||
(match: NSTextCheckingResult!, flags: NSMatchingFlags, stop: UnsafeMutablePointer<ObjCBool>) in
|
let matchRange = match!.range
|
||||||
|
|
||||||
let matchRange = match.range
|
|
||||||
out.appendString( self.substring(NSRange(location:pos, length:matchRange.location-pos))!)
|
out.appendString( self.substring(NSRange(location:pos, length:matchRange.location-pos))!)
|
||||||
out.appendString( substitution(match, stop) )
|
out.appendString( substitution(match!, stop) )
|
||||||
pos = matchRange.location + matchRange.length
|
pos = matchRange.location + matchRange.length
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -158,7 +156,7 @@ public class SwiftRegex: NSObject, BooleanType {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public var boolValue: Bool {
|
public var boolValue: Bool {
|
||||||
return doesMatch()
|
return doesMatch(nil)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -170,7 +168,7 @@ extension String {
|
|||||||
|
|
||||||
extension String {
|
extension String {
|
||||||
public subscript(pattern: String) -> SwiftRegex {
|
public subscript(pattern: String) -> SwiftRegex {
|
||||||
return SwiftRegex(target: self, pattern: pattern)
|
return SwiftRegex(target: self, pattern: pattern, options: nil)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -178,7 +176,7 @@ public func ~= (left: SwiftRegex, right: String) -> String {
|
|||||||
return left.substituteMatches({match, stop in
|
return left.substituteMatches({match, stop in
|
||||||
return left.regex.replacementStringForResult( match,
|
return left.regex.replacementStringForResult( match,
|
||||||
inString: left.target as String, offset: 0, template: right )
|
inString: left.target as String, offset: 0, template: right )
|
||||||
}, options: nil)
|
}, options: [])
|
||||||
}
|
}
|
||||||
|
|
||||||
public func ~= (left: SwiftRegex, right: [String]) -> String {
|
public func ~= (left: SwiftRegex, right: [String]) -> String {
|
||||||
@ -191,7 +189,7 @@ public func ~= (left: SwiftRegex, right: [String]) -> String {
|
|||||||
|
|
||||||
return left.regex.replacementStringForResult( match,
|
return left.regex.replacementStringForResult( match,
|
||||||
inString: left.target as String, offset: 0, template: right[matchNumber-1] )
|
inString: left.target as String, offset: 0, template: right[matchNumber-1] )
|
||||||
}, options: nil)
|
}, options: [])
|
||||||
}
|
}
|
||||||
|
|
||||||
public func ~= (left: SwiftRegex, right: (String) -> String) -> String {
|
public func ~= (left: SwiftRegex, right: (String) -> String) -> String {
|
||||||
@ -199,11 +197,11 @@ public func ~= (left: SwiftRegex, right: (String) -> String) -> String {
|
|||||||
return left.substituteMatches(
|
return left.substituteMatches(
|
||||||
{match, stop -> String in
|
{match, stop -> String in
|
||||||
right(left.substring(match.range)!)
|
right(left.substring(match.range)!)
|
||||||
}, options: nil)
|
}, options: [])
|
||||||
}
|
}
|
||||||
|
|
||||||
public func ~= (left: SwiftRegex, right: ([String]?) -> String) -> String {
|
public func ~= (left: SwiftRegex, right: ([String]?) -> String) -> String {
|
||||||
return left.substituteMatches({match, stop -> String in
|
return left.substituteMatches({match, stop -> String in
|
||||||
return right(left.groupsForMatch(match))
|
return right(left.groupsForMatch(match))
|
||||||
}, options: nil)
|
}, options: [])
|
||||||
}
|
}
|
||||||
|
|||||||
@ -169,7 +169,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
//private method that starts the connection
|
//private method that starts the connection
|
||||||
private func createHTTPRequest() {
|
private func createHTTPRequest() {
|
||||||
|
|
||||||
let str: NSString = url.absoluteString!
|
let str: NSString = url.absoluteString
|
||||||
let urlRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, "GET",
|
let urlRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, "GET",
|
||||||
url, kCFHTTPVersion1_1)
|
url, kCFHTTPVersion1_1)
|
||||||
|
|
||||||
@ -185,7 +185,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
if self.cookies != nil {
|
if self.cookies != nil {
|
||||||
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(self.cookies!)
|
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(self.cookies!)
|
||||||
for (key, value) in headers {
|
for (key, value) in headers {
|
||||||
self.addHeader(urlRequest, key: key as! String, val: value as! String)
|
self.addHeader(urlRequest, key: key as String, val: value as String)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -196,14 +196,14 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
}
|
}
|
||||||
self.addHeader(urlRequest, key: headerWSVersionName, val: headerWSVersionValue)
|
self.addHeader(urlRequest, key: headerWSVersionName, val: headerWSVersionValue)
|
||||||
self.addHeader(urlRequest, key: headerWSKeyName, val: self.generateWebSocketKey())
|
self.addHeader(urlRequest, key: headerWSKeyName, val: self.generateWebSocketKey())
|
||||||
self.addHeader(urlRequest, key: headerOriginName, val: url.absoluteString!)
|
self.addHeader(urlRequest, key: headerOriginName, val: url.absoluteString)
|
||||||
self.addHeader(urlRequest, key: headerWSHostName, val: "\(url.host!):\(port!)")
|
self.addHeader(urlRequest, key: headerWSHostName, val: "\(url.host!):\(port!)")
|
||||||
for (key,value) in headers {
|
for (key,value) in headers {
|
||||||
self.addHeader(urlRequest, key: key, val: value)
|
self.addHeader(urlRequest, key: key, val: value)
|
||||||
}
|
}
|
||||||
|
|
||||||
let serializedRequest: NSData = CFHTTPMessageCopySerializedMessage(urlRequest.takeUnretainedValue()).takeUnretainedValue()
|
let serializedRequest = CFHTTPMessageCopySerializedMessage(urlRequest.takeUnretainedValue())?.takeUnretainedValue()
|
||||||
self.initStreamsWithData(serializedRequest, Int(port!))
|
self.initStreamsWithData(serializedRequest!, Int(port!))
|
||||||
}
|
}
|
||||||
//Add a header to the CFHTTPMessage by using the NSString bridges to CFString
|
//Add a header to the CFHTTPMessage by using the NSString bridges to CFString
|
||||||
private func addHeader(urlRequest: Unmanaged<CFHTTPMessage>,key: String, val: String) {
|
private func addHeader(urlRequest: Unmanaged<CFHTTPMessage>,key: String, val: String) {
|
||||||
@ -221,8 +221,8 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
let uni = UnicodeScalar(UInt32(97 + arc4random_uniform(25)))
|
let uni = UnicodeScalar(UInt32(97 + arc4random_uniform(25)))
|
||||||
key += "\(Character(uni))"
|
key += "\(Character(uni))"
|
||||||
}
|
}
|
||||||
var data = key.dataUsingEncoding(NSUTF8StringEncoding)
|
let data = key.dataUsingEncoding(NSUTF8StringEncoding)
|
||||||
var baseKey = data?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(0))
|
let baseKey = data?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
|
||||||
return baseKey!
|
return baseKey!
|
||||||
}
|
}
|
||||||
//Start the stream connection and write the data to the output stream
|
//Start the stream connection and write the data to the output stream
|
||||||
@ -260,7 +260,7 @@ 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
|
||||||
@ -300,7 +300,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
///handles the incoming bytes and sending them to the proper processing method
|
///handles the incoming bytes and sending them to the proper processing method
|
||||||
private func processInputStream() {
|
private func processInputStream() {
|
||||||
let buf = NSMutableData(capacity: BUFFER_MAX)
|
let buf = NSMutableData(capacity: BUFFER_MAX)
|
||||||
var buffer = UnsafeMutablePointer<UInt8>(buf!.bytes)
|
let buffer = UnsafeMutablePointer<UInt8>(buf!.bytes)
|
||||||
let length = inputStream!.read(buffer, maxLength: BUFFER_MAX)
|
let length = inputStream!.read(buffer, maxLength: BUFFER_MAX)
|
||||||
if length > 0 {
|
if length > 0 {
|
||||||
if !connected {
|
if !connected {
|
||||||
@ -333,7 +333,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
let data = inputQueue[0]
|
let data = inputQueue[0]
|
||||||
var work = data
|
var work = data
|
||||||
if (fragBuffer != nil) {
|
if (fragBuffer != nil) {
|
||||||
var combine = NSMutableData(data: fragBuffer!)
|
let combine = NSMutableData(data: fragBuffer!)
|
||||||
combine.appendData(data)
|
combine.appendData(data)
|
||||||
work = combine
|
work = combine
|
||||||
fragBuffer = nil
|
fragBuffer = nil
|
||||||
@ -388,8 +388,8 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response)
|
let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response)
|
||||||
let headers: NSDictionary = cfHeaders.takeRetainedValue()
|
let headers:NSDictionary? = cfHeaders?.takeRetainedValue()
|
||||||
let acceptKey = headers[headerWSAcceptName] as! NSString
|
let acceptKey = headers?[headerWSAcceptName] as! NSString
|
||||||
if acceptKey.length > 0 {
|
if acceptKey.length > 0 {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
@ -398,7 +398,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
|
|
||||||
///process the websocket data
|
///process the websocket data
|
||||||
private func processRawMessage(buffer: UnsafePointer<UInt8>, bufferLen: Int) {
|
private func processRawMessage(buffer: UnsafePointer<UInt8>, bufferLen: Int) {
|
||||||
var response = readStack.last
|
let response = readStack.last
|
||||||
if response != nil && bufferLen < 2 {
|
if response != nil && bufferLen < 2 {
|
||||||
fragBuffer = NSData(bytes: buffer, length: bufferLen)
|
fragBuffer = NSData(bytes: buffer, length: bufferLen)
|
||||||
return
|
return
|
||||||
@ -414,7 +414,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
resp.bytesLeft -= len
|
resp.bytesLeft -= len
|
||||||
resp.buffer?.appendData(NSData(bytes: buffer, length: len))
|
resp.buffer?.appendData(NSData(bytes: buffer, length: len))
|
||||||
processResponse(resp)
|
processResponse(resp)
|
||||||
var offset = bufferLen - extra
|
let offset = bufferLen - extra
|
||||||
if extra > 0 {
|
if extra > 0 {
|
||||||
processExtra((buffer+offset), bufferLen: extra)
|
processExtra((buffer+offset), bufferLen: extra)
|
||||||
}
|
}
|
||||||
@ -473,7 +473,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
let len = Int(payloadLen-2)
|
let len = Int(payloadLen-2)
|
||||||
if len > 0 {
|
if len > 0 {
|
||||||
let bytes = UnsafePointer<UInt8>((buffer+offset))
|
let bytes = UnsafePointer<UInt8>((buffer+offset))
|
||||||
var str: NSString? = NSString(data: NSData(bytes: bytes, length: len), encoding: NSUTF8StringEncoding)
|
let str: NSString? = NSString(data: NSData(bytes: bytes, length: len), encoding: NSUTF8StringEncoding)
|
||||||
if str == nil {
|
if str == nil {
|
||||||
code = CloseCode.ProtocolError.rawValue
|
code = CloseCode.ProtocolError.rawValue
|
||||||
}
|
}
|
||||||
@ -603,7 +603,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
let data = response.buffer! //local copy so it is perverse for writing
|
let data = response.buffer! //local copy so it is perverse for writing
|
||||||
dequeueWrite(data, code: OpCode.Pong)
|
dequeueWrite(data, code: OpCode.Pong)
|
||||||
} else if response.code == .TextFrame {
|
} else if response.code == .TextFrame {
|
||||||
var str: NSString? = NSString(data: response.buffer!, encoding: NSUTF8StringEncoding)
|
let str: NSString? = NSString(data: response.buffer!, encoding: NSUTF8StringEncoding)
|
||||||
if str == nil {
|
if str == nil {
|
||||||
writeError(CloseCode.Encoding.rawValue)
|
writeError(CloseCode.Encoding.rawValue)
|
||||||
return false
|
return false
|
||||||
@ -640,7 +640,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
///write a an error to the socket
|
///write a an error to the socket
|
||||||
private func writeError(code: UInt16) {
|
private func writeError(code: UInt16) {
|
||||||
let buf = NSMutableData(capacity: sizeof(UInt16))
|
let buf = NSMutableData(capacity: sizeof(UInt16))
|
||||||
var buffer = UnsafeMutablePointer<UInt16>(buf!.bytes)
|
let buffer = UnsafeMutablePointer<UInt16>(buf!.bytes)
|
||||||
buffer[0] = code.byteSwapped
|
buffer[0] = code.byteSwapped
|
||||||
dequeueWrite(NSData(bytes: buffer, length: sizeof(UInt16)), code: .ConnectionClose)
|
dequeueWrite(NSData(bytes: buffer, length: sizeof(UInt16)), code: .ConnectionClose)
|
||||||
}
|
}
|
||||||
@ -675,12 +675,12 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
buffer[1] = CUnsignedChar(dataLength)
|
buffer[1] = CUnsignedChar(dataLength)
|
||||||
} else if dataLength <= Int(UInt16.max) {
|
} else if dataLength <= Int(UInt16.max) {
|
||||||
buffer[1] = 126
|
buffer[1] = 126
|
||||||
var sizeBuffer = UnsafeMutablePointer<UInt16>((buffer+offset))
|
let sizeBuffer = UnsafeMutablePointer<UInt16>((buffer+offset))
|
||||||
sizeBuffer[0] = UInt16(dataLength).byteSwapped
|
sizeBuffer[0] = UInt16(dataLength).byteSwapped
|
||||||
offset += sizeof(UInt16)
|
offset += sizeof(UInt16)
|
||||||
} else {
|
} else {
|
||||||
buffer[1] = 127
|
buffer[1] = 127
|
||||||
var sizeBuffer = UnsafeMutablePointer<UInt64>((buffer+offset))
|
let sizeBuffer = UnsafeMutablePointer<UInt64>((buffer+offset))
|
||||||
sizeBuffer[0] = UInt64(dataLength).byteSwapped
|
sizeBuffer[0] = UInt64(dataLength).byteSwapped
|
||||||
offset += sizeof(UInt64)
|
offset += sizeof(UInt64)
|
||||||
}
|
}
|
||||||
@ -699,7 +699,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
let writeBuffer = UnsafePointer<UInt8>(frame!.bytes+total)
|
let writeBuffer = UnsafePointer<UInt8>(frame!.bytes+total)
|
||||||
var len = self.outputStream?.write(writeBuffer, maxLength: offset-total)
|
let len = self.outputStream?.write(writeBuffer, maxLength: offset-total)
|
||||||
if len == nil || len! < 0 {
|
if len == nil || len! < 0 {
|
||||||
var error: NSError?
|
var error: NSError?
|
||||||
if let streamError = self.outputStream?.streamError {
|
if let streamError = self.outputStream?.streamError {
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user