www.webdeveloper.com
Results 1 to 2 of 2

Thread: HTML5 websockets

Hybrid View

  1. #1
    Join Date
    Jun 2012
    Posts
    2

    HTML5 websockets

    Hello

    I was trying to deal with websockets using Jetty as the websocket server
    I created a sample Stockticker Servlet example which generates price list every 5 seconds.


    For that first I created a POM file
    Code:
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>main.java.org.demoServlet.app</groupId>
      <artifactId>html5-webapp</artifactId>
      <packaging>war</packaging>
      <version>1.0-SNAPSHOT</version>
      <name>html5-webapp Maven Webapp</name>
      <url>http://maven.apache.org</url>
      <description>a project hosting an html5 webapp on jetty</description>
      <build>
        <finalName>html5-webapp</finalName>
        <plugins>
          <plugin>
            <!-- This plugin is needed for the servlet example -->
            <groupId>org.mortbay.jetty</groupId>
            <artifactId>jetty-maven-plugin</artifactId>
            <version>${jetty.version}</version>
            <configuration>
              <scanIntervalSeconds>10</scanIntervalSeconds>
              <webAppConfig>
                <contextPath>/html5-webapp</contextPath>
                <descriptor>${basedir}/src/main/webapp/web.xml</descriptor>
              </webAppConfig>
            </configuration>
          </plugin>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
              <fork>true</fork>
              <meminitial>128m</meminitial>
              <maxmem>512m</maxmem>
              <source>1.6</source>
              <target>1.6</target>
              <minmemory>256m</minmemory>
              <maxmemory>2048m</maxmemory>
            </configuration>
          </plugin>
        </plugins>
      </build>
      <properties>
        <jetty.version>8.1.2.v20120308</jetty.version>
      </properties>
    
      <dependencies>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.4</version>
          <scope>test</scope>
        </dependency>
        <dependency>
          <groupId>org.eclipse.jetty</groupId>
          <artifactId>jetty-server</artifactId>
          <version>${jetty.version}</version>
        </dependency>
        <dependency>
          <groupId>org.eclipse.jetty</groupId>
          <artifactId>jetty-websocket</artifactId>
          <version>${jetty.version}</version>
        </dependency>
      </dependencies>
    </project>
    This is for jetty server . I used Eclipse as the IDE with run-jetty-run plug-in to run the jetty server.
    Next was the servlet which extends WebSocketServlet it is html5servlet .
    which uses doWebSocketConnect method for returning a websocket
    doWebSocketConnect(HttpServletRequest req, String resp)
    code for html5servlet is
    Code:
    package main.java.org.demoServlet.app;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.concurrent.atomic.AtomicInteger;
    
    import javax.servlet.http.HttpServletRequest;
    
    import org.eclipse.jetty.websocket.WebSocket;
    import org.eclipse.jetty.websocket.WebSocketServlet;
    
    public class Html5Servlet extends WebSocketServlet {
    
    	private AtomicInteger index = new AtomicInteger();
    
    	private static final List<String> tickers = new ArrayList<String>();
    	static{
    		tickers.add("vaibhav");
    		tickers.add("JSAG");
    		tickers.add("nitin");
    		tickers.add("rahul");
    	}
    
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;
    
    	public WebSocket doWebSocketConnect(HttpServletRequest req, String resp) {
    		System.out.println("On server");
    		return new StockTickerSocket();
    	}
    	protected String getMyJsonTicker(){
    		StringBuilder start=new StringBuilder("{");
    		start.append("\"stocks\":[");
    		int counter=0;
    		for (String aTicker : tickers) {
    			counter++;
    			
    			start.append("{ \"ticker\":\""+aTicker +"\""+","+"\"price\":\""+index.incrementAndGet()+"\" }");
    			if(counter<tickers.size()){
    				start.append(",");
    			}
    		}
    		start.append("]");
    		start.append("}");
    		return start.toString();
    	}
    	
    	
    
    }

    Next is the StockTicketServlet class which implements OnFrame interface which is the extension of WebSocket and which overrides the websocket methods
    code for StockTicketServlet is
    Code:
    package main.java.org.demoServlet.app;
    
    import java.io.IOException;
    import java.util.Date;
    import java.util.Timer;
    import java.util.TimerTask;
    
    import org.eclipse.jetty.websocket.WebSocket.OnFrame;
    
    public class StockTickerSocket extends Html5Servlet implements OnFrame
    {
    
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;
    	private Connection outbound;
    	Timer timer; 
    	public void onOpen(Connection outbound) {
    		this.outbound=outbound;
    		timer=new Timer();
    	}
    
    	public void onClose() {
    		timer.cancel();
    	}
    
    	public void onFragment(boolean arg0, byte arg1, byte[] arg2, int arg3,
    			int arg4) {
    		// TODO Auto-generated method stub
    		
    	}
    	
    	/**
    	 * Message Transfer
    	 * onMessage
    	 * @param data
    	 */
    	
    	public void onFrame(String data) {
    		if(data.indexOf("disconnect")>=0){
    			outbound.disconnect();
    		}else{
    			timer.schedule(new TimerTask() {
    					
    					@Override
    					public void run() {
    						try{
    							System.out.println("Running task");
    							outbound.sendMessage(getMyJsonTicker());
    						}
    						catch (IOException e) {
    							e.printStackTrace();
    						}
    					}
    				}, new Date(),5000);
    
    		}
    		
    	}
    
    	public void onMessage(byte arg0, byte[] arg1, int arg2, int arg3) {
    		// TODO Auto-generated method stub
    		
    	}
    
    	@Override
    	public void onClose(int arg0, String arg1) {
    		// TODO Auto-generated method stub
    		
    	}
    
    	
    
    	@Override
    	public boolean onFrame(byte arg0, byte arg1, byte[] arg2, int arg3, int arg4) {
    		// TODO Auto-generated method stub
    		return false;
    	}
    
    	@Override
    	public void onHandshake(FrameConnection arg0) {
    		// TODO Auto-generated method stub
    		
    	}
    
    	
    
    	
    	
    }
    Next i wanted to create a jsp file for actual web socket call
    code for this jsp is
    Code:
    <html>
    <meta charset="utf-8" />
    <head>
    <title>WebSocket Test</title>
    <style type="text/css">
    .info {
    	color: #01529B;
    	background-color: #BDE5F8;
    }
    .error {
    	color: #D8000C;
    	background-color: #FFBABA;
    }
    
    
    </style>
    </head>
    
    <script type="text/javascript">
    
      var wsUri = "ws://localhost:"+<%=request.getLocalPort()%>+"/JettyWebsocketTicket/hello-html5";
      var output;
    
      function init()
      {
        output = document.getElementById("output");
        writeToScreen(" Not Connected to server",'warning');
        testWebSocket();
      }
      function stop()
      {
    	  websocket.send('disconnect');
      }
      function testWebSocket()
      {
        websocket = new WebSocket(wsUri);
        websocket.onopen = function(evt) { onOpen(evt) };
        websocket.onclose = function(evt) { onClose(evt) };
        websocket.onmessage = function(evt) { onMessage(evt) };
        websocket.onerror = function(evt) { onError(evt) };
      }
    
      function onOpen(evt)
      {
        writeToScreen("Connected to server");
        doSend("Hello are you there WebSocket Server");
      }
    
      function onClose(evt)
      {
        writeToScreen("Closed",'warning');
      }
    
      function onMessage(evt)
      {
    	var evalStocks = eval('(' + evt.data + ')');
    	var aTable="<table><tr><th>Ticker</th><th>Price</th></tr>";
    	for(var i=0;i<evalStocks.stocks.length;i++){
    		aTable=aTable+"<tr>";
    		aTable=aTable+"<td>";
    		aTable=aTable+evalStocks.stocks[i].ticker;
    		aTable=aTable+"</td>";
    		aTable=aTable+"<td>";
    		aTable=aTable+evalStocks.stocks[i].price;
    		aTable=aTable+"</td>";		
    		aTable=aTable+"</tr>";
    	}
    	aTable=aTable+"</table>";
        writeToScreen(aTable,'info');
      }
    
      function onError(evt)
      {
    	  writeToScreen(evt.data,'error');
      }
    
      function doSend(message)
      {
        writeToScreen("SENT: " + message); 
        websocket.send(message);
      }
    
      function writeToScreen(message,rule)
      {
        output.innerHTML=message;
        output.className=rule;
      }
      if(window.addEventListener){
    	  window.addEventListener("load", init, false);
      }else{
    	  window.attachEvent("onload", init);
      }
      
    
    </script>
    <body onload="init">
    <h3>Hello HTML5 Web Socket</h3>
    <input type="button" value="stop" name="stopBtn" onclick="stop();"/>
    <div id="output">
    </div>
    
    
    
    
    </body>
    </html>

    Everything works fine ... I start the server .. It gets connected and displays Message Hello are you there WebSocket Server" that means onOpen event is called . But after that nothing happens . Ideally it should start posting prices every five seconds on the page. but nothing happens.
    I am stuck for long and unable to debug the thing as well.
    I urge to please help me out to fix this bug.

  2. #2
    Join Date
    Jun 2012
    Posts
    2
    @Gular : what do you mean ?

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles