2013年12月19日木曜日

WebSocketの使い方と実際に使えそうなアプリを考えてみる

に(ry

Hello world.

B14(B3)のSasakiです.

本日12/19はわたしが更新します.


ちゅーわけで WebSocket
ってなんですか!?!?
  • 通信規格のひとつ
  • 1つのコネクションで全てのデータの送受信ができる.
そういうことです。 WebSocketの接続を確立するためには,
クライアント側はハンドシェイク要求を送信,
サーバ側はハンドシェイク応答
を返さなければなりません。

以下はウェブブラウザがサーバに送る要求
GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: AAA
Origin: http://example.com
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
サーバ側が返す応答
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: BBB
Sec-WebSocket-Protocol: chat



…という感じで、接続が確立できるます.


で、WebSocketにはJavaScriptAPIが用意されてます.
これが、比較的充実している模様.
IE FireFox Chrome Safari iOS Safari Android Browser
10.0 6.0 12.1 ×


WebSocket接続を確立する。
  //接続開始
  var ws = new WebSocket('ws://localhost:2000/chat');

  //確立したら呼び出される
  ws.onopen = dunction(){};

  //データの送信
  ws.send('Hello');

  //データが到着したら呼び出される
  ws.onmessage = function(e){
    var data = e.data;
  }

  //接続を切る(クライアントから)
  ws.close();

  //(サーバから)データがついたら呼出し
  ws.onclose = function(e){
    var wasClean = e.wasClean; 
    var code = e.code;
    var reason = e.reason;
  }


などなどの基本操作がAPIとして用意されてます.

めっちゃ便利.



で、そもそも、何に使えんのこれ、って話です


ミソは、大量のデータをサーバに送れること
であると思ってます.
で、双方向通信なのでサーバからクライアントにもデータ渡したりができる(?)の.

つまり、
  • チャット→多数のテキストデータを送信/DBに更新があったらクライアントに反映
  • おえかき→常に動くカーソルの座標を送信し続ける/カーソルの動きが他のクライアントから見られる

などのサービスに用いられるのですね.


ちなみに,実装において一番ポピュラーなのはnode.jsだそう.
phpでもできます.


実装編は、また今度ということで許してください.

4 件のコメント:

  1. There are six trials instead of five in the new word hurdle, which is exactly what you'd expect. For some reason, the correct letters are highlighted in blue instead of green.

    返信削除
  2. Nice post
    As a leading provider of translation services in Malaysia, Malaysiatranslators.com has a team of highly qualified Kuching-based translators who are experts in their field. They have a deep understanding of the local culture and are able to translate documents in a way that is culturally sensitive and accurate.

    返信削除
  3. Excellent post!
    Assignmenthelper.my is a reputable online platform that offers students assistance with their academic assignments at affordable prices. The site's assignment helper price is competitive, making it possible for students to receive high-quality assistance without breaking the bank. The platform boasts a team of experienced writers who specialize in different academic fields, ensuring that students receive assistance tailored to their specific needs.

    返信削除