merge master

This commit is contained in:
Erik 2015-04-08 21:16:56 -04:00
commit 01e5e22e0b
12 changed files with 287 additions and 257 deletions

View File

@ -35,6 +35,8 @@ SocketIOClient* socket = [[SocketIOClient alloc] initWithSocketURL:@"localhost:8
});
}];
[socket connect];
```
##Features

View File

@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = "Socket.IO-Client-Swift"
s.version = "1.5.1"
s.version = "2.0.0"
s.summary = "Socket.IO-client for Swift"
s.description = <<-DESC
Socket.IO-client for Swift.
@ -12,7 +12,7 @@ Pod::Spec.new do |s|
s.author = { "Erik" => "nuclear.ace@gmail.com" }
s.ios.deployment_target = '8.0'
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.requires_arc = true
# s.dependency 'Starscream', '~> 0.9' # currently this repo includes Starscream swift files

View File

@ -24,9 +24,6 @@
import Foundation
public typealias AckCallback = @objc_block (NSArray?) -> Void
public typealias OnAckCallback = (timeout:UInt64, callback:AckCallback) -> Void
struct SocketAckMap {
private var acks = [Int: AckCallback]()
private var waiting = [Int: Bool]()

View File

@ -26,24 +26,14 @@ import Foundation
extension String {
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 {
private typealias Probe = (msg:String, type:PacketType, data:ContiguousArray<NSData>?)
private typealias ProbeWaitQueue = [Probe]
private let workQueue = NSOperationQueue()
private let emitQueue = dispatch_queue_create(
"engineEmitQueue".cStringUsingEncoding(NSUTF8StringEncoding), DISPATCH_QUEUE_SERIAL)
@ -84,6 +74,24 @@ public class SocketEngine: NSObject, WebSocketDelegate {
}
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,
forceWebsockets:Bool, withCookies cookies:[NSHTTPCookie]?) {
self.client = client
@ -147,7 +155,7 @@ public class SocketEngine: NSObject, WebSocketDelegate {
urlWebSocket += "&\(keyEsc)="
if value is String {
let valueEsc = (value as String).stringByAddingPercentEncodingWithAllowedCharacters(
let valueEsc = (value as! String).stringByAddingPercentEncodingWithAllowedCharacters(
NSCharacterSet.URLHostAllowedCharacterSet())!
urlPolling += "\(valueEsc)"
urlWebSocket += "\(valueEsc)"
@ -227,6 +235,7 @@ public class SocketEngine: NSObject, WebSocketDelegate {
}
self?.waitingForPoll = false
if self!.fastUpgrade {
self?.doFastUpgrade()
return
@ -266,7 +275,7 @@ public class SocketEngine: NSObject, WebSocketDelegate {
var postStr = ""
for packet in self.postWait {
let len = countElements(packet)
let len = count(packet)
postStr += "\(len):\(packet)"
}
@ -320,6 +329,7 @@ public class SocketEngine: NSObject, WebSocketDelegate {
}
// A poll failed, tell the client about it
private func handlePollingFailed(reason:String) {
self._connected = false
self.ws?.disconnect()
@ -441,10 +451,76 @@ public class SocketEngine: NSObject, WebSocketDelegate {
fixDoubleUTF8(&message)
}
let type = message["^(\\d)"].groups()?[1]
let type = PacketType(str: (message["^(\\d)"].groups()?[1])!)
if type != PacketType.MESSAGE.rawValue {
// TODO Handle other packets
if type == PacketType.MESSAGE {
// Remove message type
message.removeAtIndex(message.startIndex)
if self.client == nil {
return
}
dispatch_async(self.client!.handleQueue) {[weak self] in
self?.client?.parseSocketMessage(message)
return
}
} else if type == PacketType.NOOP {
self.doPoll()
return
} else if type == PacketType.PONG {
// We should upgrade
if message == "3probe" {
self.upgradeTransport()
return
}
return
} else if type == PacketType.OPEN {
var err:NSError?
message.removeAtIndex(message.startIndex)
let mesData = message.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
if let json = NSJSONSerialization.JSONObjectWithData(mesData,
options: NSJSONReadingOptions.AllowFragments, error: &err) as? NSDictionary {
if let sid = json["sid"] as? String {
// println(json)
self.sid = sid
self._connected = true
if !self.forcePolling && !self.forceWebsockets {
self.createWebsocket(andConnect: true)
}
} else {
NSLog("Error handshaking")
return
}
if let pingInterval = json["pingInterval"] as? Int {
self.pingInterval = pingInterval / 1000
}
} else {
fatalError("Error parsing engine connect")
}
self.startPingTimer()
if !self.forceWebsockets {
self.doPoll()
}
return
} else if type == PacketType.CLOSE {
if self.client == nil {
return
}
if self.polling {
self.client!.engineDidForceClose("Disconnect")
}
return
} else {
if message.hasPrefix("b4") {
// binary in base64 string
@ -452,91 +528,16 @@ public class SocketEngine: NSObject, WebSocketDelegate {
end: advance(message.startIndex, 2)))
if let data = NSData(base64EncodedString: message,
options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters) {
options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)
where self.client != nil {
// println("sending \(data)")
if self.client == nil {
return
}
dispatch_async(self.client!.handleQueue) {[weak self] in
self?.client?.parseBinaryData(data)
return
}
}
return
} else if type == PacketType.NOOP.rawValue {
self.doPoll()
return
} else if type == PacketType.PONG.rawValue {
// We should upgrade
if message == "3probe" {
self.upgradeTransport()
return
}
return
} else if type == PacketType.OPEN.rawValue {
var err:NSError?
message.removeAtIndex(message.startIndex)
let mesData = message.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
if let json = NSJSONSerialization.JSONObjectWithData(mesData,
options: NSJSONReadingOptions.AllowFragments, error: &err) as? NSDictionary {
if let sid = json["sid"] as? String {
// println(json)
self.sid = sid
self._connected = true
if !self.forcePolling && !self.forceWebsockets {
self.createWebsocket(andConnect: true)
}
} else {
self.client?.engineDidError("Error parsing engine connect")
return
}
if let pingInterval = json["pingInterval"] as? Int {
self.pingInterval = pingInterval / 1000
}
} else {
self.client?.engineDidError("Error parsing engine connect")
return
}
self.startPingTimer()
if !self.forceWebsockets {
self.doPoll()
}
return
} else if type == PacketType.CLOSE.rawValue {
if self.client == nil {
return
}
if self.polling {
self.client!.engineDidForceClose("Disconnect")
}
return
}
// println("Got something idk what to do with")
// println(messageString)
}
// Remove message type
message.removeAtIndex(message.startIndex)
if self.client == nil {
return
}
dispatch_async(self.client!.handleQueue) {[weak self] in
self?.client?.parseSocketMessage(message)
return
}
}

View File

@ -24,9 +24,6 @@
import Foundation
public typealias NormalCallback = (NSArray?, AckEmitter?) -> Void
public typealias AckEmitter = (AnyObject...) -> Void
private func emitAckCallback(socket:SocketIOClient, num:Int)
// Curried
(items:AnyObject...) -> Void {

View File

@ -3,6 +3,7 @@
// Socket.IO-Swift
//
// Created by Erik Little on 3/16/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

View File

@ -195,7 +195,7 @@ public class SocketIOClient: NSObject, SocketEngineClient {
return
}
self?.ackHandlers.addAck(ack, callback)
self?.ackHandlers.addAck(ack, callback: callback)
dispatch_async(self!.emitQueue) {
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)
var str:String
let str:String
SocketParser.parseForEmit(packet)
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)
var str:String
let str:String
SocketParser.parseForEmit(packet)
str = packet.createAck()
@ -349,7 +349,7 @@ public class SocketIOClient: NSObject, SocketEngineClient {
var ackData:[AnyObject]?
if data is NSArray {
ackData = data as? NSArray
ackData = (data as? [AnyObject]?)!
} else if data != nil {
ackData = [data!]
}

View File

@ -24,24 +24,6 @@
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 {
var binary = ContiguousArray<NSData>()
var currentPlace = 0
@ -62,7 +44,7 @@ class SocketPacket {
}
func getEvent() -> String {
return data?.removeAtIndex(0) as String
return data?.removeAtIndex(0) as! String
}
func addData(data:NSData) -> Bool {
@ -90,7 +72,7 @@ class SocketPacket {
}
func createMessageForEvent(event:String) -> String {
var message:String
let message:String
var jsonSendError:NSError?
if self.binary.count == 0 {
@ -164,7 +146,6 @@ class SocketPacket {
}
for arg in self.data! {
if arg is NSDictionary || arg is [AnyObject] {
let jsonSend = NSJSONSerialization.dataWithJSONObject(arg,
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 {
@ -219,7 +200,7 @@ class SocketPacket {
var newDict = NSMutableDictionary(dictionary: dict)
for (key, value) in dict {
newDict[key as NSCopying] = _fillInPlaceholders(value)
newDict[key as! NSCopying] = _fillInPlaceholders(value)
}
return newDict

View File

@ -22,9 +22,9 @@
import Foundation
private let shredder = SocketParser.PacketShredder()
class SocketParser {
private static let shredder = SocketParser.PacketShredder()
// Translation of socket.io-parser#deconstructPacket
private class PacketShredder {
var buf = ContiguousArray<NSData>()
@ -48,7 +48,7 @@ class SocketParser {
var newDict = NSMutableDictionary(dictionary: dict)
for (key, value) in newDict {
newDict[key as NSCopying] = shred(value)
newDict[key as! NSCopying] = shred(value)
}
return newDict
@ -148,7 +148,7 @@ class SocketParser {
let d = String(arr[++i...arr.count-1])
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,
nsp: nsp, placeholders: placeholders, id: id)

52
SwiftIO/SocketTypes.swift Normal file
View 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)!
}
}
}

View File

@ -43,7 +43,7 @@ public class SwiftRegex: NSObject, BooleanType {
}
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? {
@ -138,7 +138,7 @@ public class SwiftRegex: NSObject, BooleanType {
return out
}
func substituteMatches(substitution: (NSTextCheckingResult, UnsafeMutablePointer<ObjCBool>) -> String,
func substituteMatches(substitution: ((NSTextCheckingResult, UnsafeMutablePointer<ObjCBool>) -> String),
options:NSMatchingOptions = nil) -> String {
let out = NSMutableString()
var pos = 0

View File

@ -7,7 +7,6 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
import Foundation
import CoreFoundation
public protocol WebSocketDelegate: class {
func websocketDidConnect(socket: WebSocket)
@ -236,8 +235,8 @@ public class WebSocket : NSObject, NSStreamDelegate {
}
if self.selfSignedSSL {
let settings: Dictionary<NSObject, NSObject> = [kCFStreamSSLValidatesCertificateChain: NSNumber(bool:false), kCFStreamSSLPeerName: kCFNull]
inputStream!.setProperty(settings, forKey: kCFStreamPropertySSLSettings)
outputStream!.setProperty(settings, forKey: kCFStreamPropertySSLSettings)
inputStream!.setProperty(settings, forKey: kCFStreamPropertySSLSettings as String)
outputStream!.setProperty(settings, forKey: kCFStreamPropertySSLSettings as String)
}
isRunLoop = true
inputStream!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
@ -247,18 +246,18 @@ public class WebSocket : NSObject, NSStreamDelegate {
let bytes = UnsafePointer<UInt8>(data.bytes)
outputStream!.write(bytes, maxLength: data.length)
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
func stream(aStream: NSStream!, handleEvent eventCode: NSStreamEvent) {
public func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent) {
if eventCode == .HasBytesAvailable {
if(aStream == inputStream) {
processInputStream()
}
} else if eventCode == .ErrorOccurred {
disconnectStream(aStream!.streamError)
disconnectStream(aStream.streamError)
} else if eventCode == .EndEncountered {
disconnectStream(nil)
}
@ -333,7 +332,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
}
///Finds the HTTP Packet in the TCP stream, by looking for the CRLF.
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 totalSize = 0
for var i = 0; i < bufferLen; i++ {
@ -376,7 +375,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
}
let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response.takeUnretainedValue())
let headers: NSDictionary = cfHeaders.takeUnretainedValue()
let acceptKey = headers[headerWSAcceptName] as NSString
let acceptKey = headers[headerWSAcceptName] as! NSString
if acceptKey.length > 0 {
return true
}
@ -500,7 +499,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
data = NSData(bytes: UnsafePointer<UInt8>((buffer+offset)), length: Int(len))
}
if receivedOpcode == OpCode.Pong.rawValue {
let step = Int(offset+len)
let step = offset + Int(len)
let extra = bufferLen-step
if extra > 0 {
processRawMessage((buffer+step), bufferLen: extra)
@ -565,7 +564,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
processResponse(response!)
}
let step = Int(offset+len)
let step = offset + Int(len)
let extra = bufferLen-step
if(extra > 0) {
processExtra((buffer+step), bufferLen: extra)
@ -597,9 +596,9 @@ public class WebSocket : NSObject, NSStreamDelegate {
}
dispatch_async(queue,{
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 {
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
var maskKey = UnsafeMutablePointer<UInt8>(buffer + offset)
SecRandomCopyBytes(kSecRandomDefault, UInt(sizeof(UInt32)), maskKey)
SecRandomCopyBytes(kSecRandomDefault, Int(sizeof(UInt32)), maskKey)
offset += sizeof(UInt32)
for (var i = 0; i < dataLength; i++) {