Quantcast
Channel: プログラム の個人的なメモ
Viewing all articles
Browse latest Browse all 860

【HTML5】WebSoket ~ 入門編 ~

$
0
0

サンプル

 * WebSoket版 の Hello World 的なものを作ってみる

クライアント側 (HTML + JavaScript)

<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>WebSocket Sample</title><script src="http://code.jquery.com/jquery-latest.min.js"></script><script>
$(function(){
    // WebSocket作成
    var webSocket = new WebSocket("ws://localhost:8080/SampleWebService/Hello");

    // WebSocket open時のイベントハンドラ登録
    webSocket.onopen = function(){
        $("#result").prepend("[onopen] " + "<br/>");
    }

    // WebSocket message受信時のイベントハンドラ登録
    webSocket.onmessage = function(message){
        $("#result").prepend(message.data + "<br/>");
    }

    // WebSocket error時のイベントハンドラ登録
    webSocket.onerror = function(){
        $("#result").prepend("[onerror] " + "<br/>");
    }

    // WebSocket close時のイベントハンドラ登録
    webSocket.onclose = function(){
        $("#result").prepend("[onclose] " + "<br/>");
    }

    // Windowが閉じられた(例:ブラウザを閉じた)時のイベントを設定
    $(window).unload(function() {
        webSocket.onclose();
    })

    // キー入力時のイベントを設定
    $("#message").keyup(function(e){
        webSocket.send($("#message").val());
    });
})</script></head><body><input type="text" id="message" /><div id="result" /></body></html

サーバ側 (Java)

import java.io.IOException;
import java.util.Set;

import javax.websocket.CloseReason;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/Hello")
public class HelloEndPoint {
  // 現在のセッションを記録
  Session currentSession = null;

  public HelloEndPoint() {
      super();
  }

  /**
   * 接続がオープンしたとき
   */
  @OnOpen
  public void onOpen(Session session, EndpointConfig endpointConfig) {
    this.currentSession = session;
  }

  /*
   * メッセージを受信したとき
   */
  @OnMessage
  public void receiveMessage(String message) throws IOException {
    // メッセージをクライアントに送信する
    this.currentSession.getBasicRemote().sendText("Hello, " + message + ".");

    Set<Session> sessions = this.currentSession.getOpenSessions();
    for (Session session : sessions) {
      try {
        session.getBasicRemote().sendText("Hello, " + message + "!!");
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
  }

  /*
   * 接続がクローズしたとき
   */
  @OnClose
  public void onClose(Session session, CloseReason reason) {
    System.out.println("onClose : " + reason.getReasonPhrase());
  }

  /*
   * 接続エラーが発生したとき
   */
  @OnError
  public void onError(Throwable throwable) {
    System.out.println("onError");
  }
}

出力結果

サーバが起動していないとき
[onclose]
[onerror]
サーバが起動しているとき(「Mike」と入力)
Hello, Mike!!
Hello, Mike.
Hello, Mik!!
Hello, Mik.
Hello, Mi!!
Hello, Mi.
Hello, M!!
Hello, M.
Hello, M!!
Hello, M.
[onopen]

Viewing all articles
Browse latest Browse all 860

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>