LoginSignup
18
18

More than 5 years have passed since last update.

Socket.IO-Client-Swiftを使ってて調べたことのメモ

Last updated at Posted at 2016-07-05

iOSでWebSocket通信をするためにSocket.IOのSwift用クライアントを利用しましたが、
ちょっとOptionの設定や受信した情報の変換で手間取ってたので覚えてるうちにメモメモ。
メモなので、個人的に必要だった部分までで終了してます。

Socket.IO-Client-Swift

https://github.com/socketio/socket.io-client-swift
記述時点のバージョンは、v6.1.4

以前の記事

SwiftでWebSocket通信のテスト
http://qiita.com/Takumi_Mori/items/390c5dae9e2a9d4290bd
実際使ってみる方法に関してはこっちで書いてます。

Options

SocketIOClientのConstructorsで指定するSocketIOClientOptionですが、
それぞれ指定したらどうなるのか全然知らないので公式の解説を翻訳しつつ...

ConnectParams([String: AnyObject])

// Dictionary whose contents will be passed with the connection.

サーバーとの接続が完了したときに、ここで指定したDictionary<String, AnyObject>が渡されます。

case Cookies([NSHTTPCookie])

// An array of NSHTTPCookies. Passed during the handshake. Default is nil.

handshakeの際に受け渡されるNSHTTPCookesの配列。
デフォルトはnil
Wikipedia:ハンドシェイク

DoubleEncodeUTF8(Bool)

// Whether or not to double encode utf8. 
If using the node based server this should be true. Default is true.

UTF8をエンコードする際に、2倍にするかどうか。ノードベースのサーバーを使用する場合、これをtrueにする必要があります。
デフォルトはtrue

ExtraHeaders([String: String])

// Adds custom headers to the initial request. Default is nil.

最初のリクエストにカスタムヘッダーを追加します。
デフォルトはnil

ForcePolling(Bool)

// `true` forces the client to use xhr-polling. Default is `false`

trueにした場合、xhr-pollingを行うようにクライアントに強制します。
デフォルトはfalse
(XHR pollingって、XMLHttpRequestでのポーリングって意味なのかな・・・。なんかtrueにすると再接続のログが多い印象)

ForceNew(Bool)

// Will a create a new engine for each connect. 
Useful if you find a bug in the engine related to reconnects

それぞれの接続のために新しいエンジンを作成します。再接続に関連する不具合を見つけた場合、便利に利用することができます。

ForceWebsockets(Bool)

// `true` forces the client to use WebSockets. Default is `false`

trueにした場合、WebSocketsを利用することをクライアントに強制します。
デフォルトはfalse

pollingによる接続は許可していなくて、WebSocketで通信を行う仕様になっていたら
これをtrueにしていないとうまく動きません。そのせいでうまく動いてませんでした。。。

HandleQueue(dispatch_queue_t)

// The dispatch queue that handlers are run on. Default is the main queue.

ハンドラを実行するときに利用するdispatch queueを指定します。
デフォルトはmain queueが指定されます。

Log(Bool)

// If `true` socket will log debug messages. Default is false.

trueにした場合、socketはログウィンドウにデバッグメッセージを表示します。
デフォルトはfalse

以下のようなログが表示されます。

2016-07-04 17:16:19.184 MyApp[9743:2389930] LOG SocketEngine: Starting engine. Server: http://localhost:8080
2016-07-04 17:16:19.184 MyApp[9743:2389930] LOG SocketEngine: Handshaking
2016-07-04 17:16:19.185 MyApp[9743:2389930] LOG SocketEnginePolling: Doing polling request
2016-07-04 17:16:19.167 MyApp[9743:2389791] LOG SocketEnginePolling: Doing polling request
2016-07-04 17:16:19.269 MyApp[9743:2389791] LOG SocketEnginePolling: Got polling response
2016-07-04 17:16:19.270 MyApp[9743:2389930] LOG SocketEnginePolling: Got polling response

Logger(SocketLogger)

// Custom logger that conforms to SocketLogger. Will use the default logging otherwise.
SocketLoggerに準拠したカスタムログ出力を利用する場合。
それ以外の場合は、デフォルトのログ出力を利用する。

Nsp(String)

// The namespace to connect to. Must begin with /. Default is `/`

接続するためのネームスペースを指定します。
必ず/.から始める必要があります。
デフォルトは/

Path(String)

// If the server uses a custom path. ex: `"/swift/"`. Default is `""`

サーバーがカスタムパスを使用している場合に指定。
例えば"/swift/"など。
デフォルトは""

Reconnects(Bool)

// Whether to reconnect on server lose. Default is `true`

サーバーとの接続が切れた場合に、再接続するかどうか。
デフォルトはtrue

ReconnectAttempts(Int)

// How many times to reconnect. Default is `-1` (infinite tries)

何回まで再接続を試みるか。
デフォルトは-1で、これは無限回施行することになる

ReconnectWait(Int)

// Amount of time to wait between reconnects. Default is `10`

再接続の間に待機する時間。
デフォルトは10秒

SessionDelegate(NSURLSessionDelegate)

// Sets an NSURLSessionDelegate for the underlying engine. 
Useful if you need to handle self-signed certs. Default is nil.

基本となるエンジンのNSURLSessionDelegateをセットします。
自己署名証明書を利用する必要がある場合などに利用できます。
デフォルトはnil

Secure(Bool)

// If the connection should use TLS. Default is false.

接続にTLSを利用する必要があるとき。
デフォルトはfalse

Security(SSLSecurity)

// Allows you to set which certs are valid. Useful for SSL pinning.

有効な証明書を設定できます。
SSL pinningで利用できます。

SelfSigned(Bool)

// Sets WebSocket.selfSignedSSL. Use this if you're using self-signed certs.

WebSocket.selfSignedSSLを設定します。
自己署名証明書を利用しているときに使います。

VoipEnabled(Bool)

// Only use this option if you're using the client with VoIP services. 
Changes the way the WebSocket is created. Default is false

VoIPサービスを利用したクライアントを使用している場合にのみ、
このオプションを使用します。WebSocketが作成される方法を変更します。
デフォルトはfalse

Methods

途中で力尽きた...

  1. on(event: String, callback: NormalCallback) -> NSUUID
    • イベントが発生したときのハンドラを追加します。
    • コールバックのアイテムは、配列(Array)の形で渡されます。
    • ack can be used to send an ack when one is requested.
    • See example. Returns a unique id for the handler.
  2. once(event: String, callback: NormalCallback) -> NSUUID
    • Adds a handler that will only be executed once.
    • Returns a unique id for the handler.
  3. onAny(callback:((event: String, items: AnyObject?)) -> Void)
    • Adds a handler for all events.
    • It will be called on any received event.
  4. emit(event: String, _ items: AnyObject...)
    • Sends a message. Can send multiple items.
  5. emit(event: String, withItems items: [AnyObject])
    • emit for Objective-C
  6. emitWithAck(event: String, _ items: AnyObject...) -> (timeoutAfter: UInt64, callback: (NSArray?) -> Void) -> Void
    • Sends a message that requests an acknowledgement from the server.
    • Returns a function which you can use to add a handler.
    • See example. Note: The message is not sent until you call the returned function.
  7. emitWithAck(event: String, withItems items: [AnyObject]) -> (UInt64, (NSArray?) -> Void) -> Void
    • emitWithAck for Objective-C.
    • Note: The message is not sent until you call the returned function.
  8. connect()
    • Establishes a connection to the server.
    • A "connect" event is fired upon successful connection.
  9. connect(timeoutAfter timeoutAfter: Int, withTimeoutHandler handler: (() -> Void)?)
    • Connect to the server.
    • If it isn't connected after timeoutAfter seconds, the handler is called.
  10. disconnect()
    • Closes the socket.
    • Reopening a disconnected socket is not fully tested.
  11. reconnect()
    • Causes the client to reconnect to the server.
  12. joinNamespace(namespace: String)
    • Causes the client to join namespace.
    • Shouldn't need to be called unless you change namespaces manually.
  13. leaveNamespace()
    • Causes the client to leave the nsp and go back to /
  14. off(event: String)
    • Removes all event handlers for event.
  15. off(id id: NSUUID)
    • Removes the event that corresponds to id.
  16. removeAllHandlers()
    • すべてのハンドラを削除します。

Client Events

  1. connect
    • Emitted when on a successful connection.
  2. disconnect
    • Emitted when the connection is closed.
  3. error
    • Emitted on an error.
  4. reconnect
    • Emitted when the connection is starting to reconnect.
  5. reconnectAttempt
    • Emitted when attempting to reconnect.
18
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
18