标签存档: html5

Java WebSocket 开发 Webbit

webbit是基于netty扩展的websocket工具。可以大大简化websocket开发。

项目地址:https://github.com/webbit/webbit

使用说明:https://github.com/webbit/webbit/blob/master/README.md

本文权当翻译,高手直接进上面链接

一些题外话:

  1. websocket和我一开始想象的TCP应用不同。websocket和传统意义上的socket通信不一样。本质上还是HTTP的扩展。
  2. websocket协议目前还没有定稿。目前主要有3个版本的协议在使用。且都是草案。webbit都实现了3个草案。具体参阅维基http://en.wikipedia.org/wiki/WebSocket

快速开始

Maven配置

<dependency>
	<groupId>org.webbitserver</groupId>
	<artifactId>webbit</artifactId>
	<version>0.4.7</version>
</dependency>

 配置端口8080.并配置websocket路径/socket的handler

public class WebSocketServer{

	public static void main(String[] args) {
		WebServer webServer = WebServers.createWebServer(8080)
	    .add(new StaticFileHandler("/socket"));
		webServer.start();
	}

}

 编写/socket handler

public class WebSocketHandler  extends BaseWebSocketHandler{

    private int connectionCount;

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

    public void onClose(WebSocketConnection connection) {
        connectionCount--;
    }

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

}

到此为止。基本代码已经都好了。感觉更写个servlet一样方便。

下面是客户端代码:

<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://' + document.location.host + '/hellowebsocket');
      showMessage('Connecting...');
      ws.onopen = function() { showMessage('Connected!'); };
      ws.onclose = function() { showMessage('Lost connection'); };
      ws.onmessage = function(msg) { showMessage(msg.data); };
    </script>
  </body>
</html>

到此为止。websocket基本功能都已经实现。