BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  37 Posts :: 3 Stories :: 24 Comments :: 0 Trackbacks
The website nettuts provides us one tutorial for HTML 5 web socket based on PHP server,as I am not familiar with PHP , I am trying some other web socket servers instead. I search the web socket server implementation and write demos to test them,but most of them cannot work.Finally I use the faye-websocket ( ) as the web socket server to let my first example work.

JavaScript Server Side

First install the module with the following command to 
get the web socket server code ( 

npm install faye-websocket

 then start the server by the command node server.js(you need to install node.js first)

var WebSocket = require('faye-websocket'),
    http      = require('http');

var server = http.createServer();

server.addListener('upgrade', function(request, socket, head) {
  var ws = new WebSocket(request, socket, head);

  ws.onmessage = function(event) {

  ws.onclose = function(event) {
    console.log('close', event.code, event.reason);
    ws = null;


Now ,come to the client,this time we are using the client code(client.html) from
<script type="text/javascript">
function connect(){
    var socket;
    var host = "ws://localhost:8888";
        socket = new WebSocket(host);
        message('<p class="event">Socket Status: '+socket.readyState);
        socket.onopen = function(){
            message('<p class="event">Socket Status: '+socket.readyState+' (open)');
        socket.onmessage = function(msg){
            message('<p class="message">Received: ';
        socket.onclose = function(){
            message('<p class="event">Socket Status: '+socket.readyState+' (Closed)');
    } catch(exception){
    function send(){
        var text = $('#text').val();
            message('<p class="warning">Please enter a message');
            return ;
            message('<p class="event">Sent: '+text)
        } catch(exception){
           message('<p class="warning">');
    function message(msg){
    $('#text').keypress(function(event) {
        if (event.keyCode == '13') {

}//End connect

$(document).ready(function() {

      if(!("WebSocket" in window)){
      $('#chatLog, input, button, #examples').fadeOut("fast");
      $('<p>Oh no, you need a browser that supports WebSockets. How about <a href="">Google Chrome</a>?</p>').appendTo('#container');
          //The user has WebSockets
      }//End else

Now you can double click the client.html and you have already connected to the web socket server. I am testing this demo using Goolge Chrome 
21.0.1180.4 dev-m,Firefox 14.0 and Safari 5.1.7 and they are working properly.


Python Server Side

There is one python implementation pywebsocket( which we can use to serve as the server. pywebsocket comes with an example in /src/example however these are aimed at the standalone mode,use the command to start the server , the client above can remian the same except the host change ,ws://localhost:8888/echo.
python mod_pywebsocket/ -p 8888 --allow-draft75 -d example --log-level debug

Java Server Side

Tomcat provides support for WebSocket from the version Tomcat 7.0 and they also give several example applications to demonstrate how to use the websocket, take the echoMessage for example, It provides one way to echo back the message which It receives. copy the EchoMessage servlet to your web project
public class EchoMessage extends WebSocketServlet {

private static final long serialVersionUID = 1L;
private volatile int byteBufSize;
private volatile int charBufSize;

public void init() throws ServletException {
= getInitParameterIntValue("byteBufferMaxSize"2097152);
= getInitParameterIntValue("charBufferMaxSize"2097152);

public int getInitParameterIntValue(String name, int defaultValue) {
        String val 
= this.getInitParameter(name);
int result;
if(null != val) {
try {
= Integer.parseInt(val);
catch (Exception x) {
= defaultValue;
else {
= defaultValue;

return result;

protected StreamInbound createWebSocketInbound(String subProtocol) {
return new EchoMessageInbound(byteBufSize,charBufSize);

private static final class EchoMessageInbound extends MessageInbound {

public EchoMessageInbound(int byteBufferMaxSize, int charBufferMaxSize) {

protected void onBinaryMessage(ByteBuffer message) throws IOException {

protected void onTextMessage(CharBuffer message) throws IOException {

configure and add the following to the web.xml

Now get connected to the server via the url  ws://localhost:8888/[ContextPath]/echo, this demo works properly in Firefox and Chrome, but fails in safari.

posted on 2012-06-22 12:28 Life is no respector of any genius. 阅读(1038) 评论(0)  编辑  收藏 所属分类: Java