试用 WebSocket

public class MyWebSocketServer extends WebSocketServer {

	private static MyWebSocketServer server;

	private static InetSocketAddress address = new InetSocketAddress(8080);

	public MyWebSocketServer() throws UnknownHostException {
		super(address);
	}

	@Override
	public void onOpen(WebSocket conn, ClientHandshake handshake) {
		System.out.println("open");
	}

	@Override
	public void onClose(WebSocket conn, int code, String reason, boolean remote) {
		System.out.println("close");
	}

	@Override
	public void onMessage(WebSocket conn, String message) {
		System.out.println(message);
		if (message.equals("close")) {
			try {
				server.stop(3000);
			} catch (IOException e) {
				e.printStackTrace();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		} else {
			conn.send(message);
		}
	}

	@Override
	public void onError(WebSocket conn, Exception ex) {
		System.out.println("error");
	}

	public static void main(String[] args) {
		try {
			server = new MyWebSocketServer();
		} catch (UnknownHostException e1) {
			e1.printStackTrace();
		}
		server.start();
	}

}
<input id="t" type="text" /><input id="b" type="button" value="Send" />
<script>
var wsServer = 'ws://192.168.56.1:8080';
var websocket = new WebSocket(wsServer);
websocket.onopen = function(evt){
	console.log("open");
	document.getElementById("b").addEventListener("click", function(evt){
		websocket.send(document.getElementById("t").value);
	}, false);
};
websocket.onclose = function(evt){
	console.log("close");
};
websocket.onmessage = function(evt){
	console.log(evt.data + " at " + evt.timeStamp);
};
websocket.onerror = function(evt){
	console.log("error");
};
</script>