webbit 簡單使用

webbit 本身的說明: A Java event based WebSocket and HTTP server
github地址:https://github.com/webbit/webbit
官方地址:http://webbitserver.org/

應用:
一、http獲取靜態文件資源
package com.sohu.common.server.webbit;

import java.util.concurrent.ExecutionException;

import org.webbitserver.WebServer;
import org.webbitserver.WebServers;
import org.webbitserver.handler.StaticFileHandler;
/**
 * webbit 實現靜態文件server,即經過
 * http獲取靜態文件
 * @author shaojieyue
 * @date 2013-08-28 11:10:52
 */
public class StaticServer {

	/**
	 * @param args
	 * @throws ExecutionException 
	 * @throws InterruptedException 
	 */
	public static void main(String[] args) throws InterruptedException, ExecutionException {
		WebServer webServer = WebServers.createWebServer(8080)
	            .add(new StaticFileHandler("/web")) // path to web content
	            .start().get();
		//test wget http://localhost:8080/web/test.txt
		//保證/web/test.txt存在
		System.out.println("web static file server start at "+webServer.getUri());
	}

}
二、HTML5 WebSocket
package com.sohu.common.server.webbit;

import org.webbitserver.BaseWebSocketHandler;
import org.webbitserver.WebServer;
import org.webbitserver.WebServers;
import org.webbitserver.WebSocketConnection;
import org.webbitserver.handler.StaticFileHandler;
/**
 * webbit 實現 HTML WebSocket server端
 * @author shaojieyue
 * @date 2013-08-28 11:12:23
 */
public class WebSocketServer {

	 public static void main(String[] args) {
		 WebServer webServer = WebServers.createWebServer(8080)
	                .add("/hellowebsocket", new WebSocketHandler());
	        webServer.start();
	        System.out.println("Server running at " + webServer.getUri());
	    }
	//實現WebSocket Handler
	static class WebSocketHandler  extends BaseWebSocketHandler {

		private int connectionCount;

	    public void onOpen(WebSocketConnection connection) {
	        connection.send("Hello! There are " + connectionCount + " other connections active");
	        System.out.println("add connectionCount="+connectionCount);
	        connectionCount++;
	    }

	    public void onClose(WebSocketConnection connection) {
	    	System.out.println("del connectionCount="+connectionCount);
	        connectionCount--;
	    }

	    public void onMessage(WebSocketConnection connection, String message) {
	        connection.send(message.toUpperCase()); // echo back message in upper case
	    }
		
	}
}

web端:
<html>
  <body>

    <!-- Send text to websocket -->
    <input id="userInput" type="text">
    <button onclick="ws.send(document.getElementById('userInput').value)">Send</button>

    <!-- Results -->
    <div id="message"></div>

    <script>
      function showMessage(text) {
        document.getElementById('message').innerHTML = text;
      }

      var ws = new WebSocket('ws://localhost:8080/hellowebsocket	');
      //alert(document.location.host);
      showMessage('Connecting...');
      ws.onopen = function() { showMessage('Connected!'); };
      ws.onclose = function() { showMessage('Lost connection'); };
      ws.onmessage = function(msg) { showMessage(msg.data); };
    </script>
  </body>
</html>

三、html5 EventSource server 實現

package com.sohu.common.server.webbit;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.webbitserver.EventSourceConnection;
import org.webbitserver.EventSourceHandler;
import org.webbitserver.EventSourceMessage;
import org.webbitserver.WebServer;
import org.webbitserver.WebServers;
import org.webbitserver.handler.EmbeddedResourceHandler;
/**
 * EventSource server端
 * @author shaojieyue
 * @date 2013-08-28 14:53:23
 */
public class EventSourceServer {
	public static class Pusher {
		private List<EventSourceConnection> connections = new ArrayList<EventSourceConnection>();
		private int count = 1;

		public void addConnection(EventSourceConnection connection) {
			connection.data("id", count++);
			connections.add(connection);
			broadcast("Client " + connection.data("id") + " joined");
		}

		public void removeConnection(EventSourceConnection connection) {
			connections.remove(connection);
			broadcast("Client " + connection.data("id") + " left");
		}

		public void pushPeriodicallyOn(ExecutorService webThread)
				throws InterruptedException, ExecutionException {
			while (true) {
				Thread.sleep(1000);
				webThread.submit(new Runnable() {
					@Override
					public void run() {
						broadcast(new Date().toString());
					}
				}).get();
			}
		}
		/**
		 * 廣播消息
		 * @param message
		 */
		private void broadcast(String message) {
			for (EventSourceConnection connection : connections) {
				connection.send(new EventSourceMessage(message));
			}
		}
	}

	public static void main(String[] args) throws Exception {
		ExecutorService webThread = Executors.newSingleThreadExecutor();
		final Pusher pusher = new Pusher();

		WebServer webServer = WebServers
				.createWebServer(webThread, 8080)
				.add("/events", new EventSourceHandler() {
					@Override
					public void onOpen(EventSourceConnection connection)
							throws Exception {
						System.out.println("--->add conn "+connection);
						pusher.addConnection(connection);
					}

					@Override
					public void onClose(EventSourceConnection connection)
							throws Exception {
						System.out.println("--->remove conn "+connection);
						pusher.removeConnection(connection);
					}
				})
				/*內置資源例如com/sohu/common/server/webbit/index.html 的訪問方式爲
				 * http://localhost:8080/index.html
				*/
				.add(new EmbeddedResourceHandler("com/sohu/common/server/webbit"))
				.start().get();
		System.out.println("EventSource demo running on: " + webServer.getUri());
		pusher.pushPeriodicallyOn(webThread);
	}
}
<!DOCTYPE html>
<html>
<head>
    <title>EventSource Demo</title>
    <script type="text/javascript">
        function logText(msg) {
            var textArea = document.getElementById('data');
            textArea.value = textArea.value + msg + '\n';
            textArea.scrollTop = textArea.scrollHeight; // scroll into view
        }


        var es = new EventSource('http://localhost:8080/events');
        es.onopen = function() {
            logText('OPEN');
        };
        es.onmessage = function(event) {
            logText(event.data);
        };
        es.onerror = function() {
            logText('ERROR');
        };
    </script>
</head>
<body>
<textarea id="data" rows="20" cols="30"></textarea>
</body>
</html>

相關文章
相關標籤/搜索