0 Replies Latest reply on Jan 20, 2015 5:40 AM by basoy1988

    Connected to websocket from java class but not run websocket methods

    basoy1988

      Hi! I run my java servlet class application in Coldfusion 11. I use websockets in my app, but its methods not run. Websockets descripion locate in javascript and use in java classes. I see message "Conection established" but methods in java class don't runs(this classes are respond for uploading percents and they don't change on html). Websockets run on port 8577, not on 8500(8500 is a default port for my Coldfusion applications), because in 8500 javascript send message "connection terminated". Full code do you see in:http://stackoverflow.com/questions/28045097/connected-to-websocket-coldfusion-from-java-cl ass-but-not-run-websocket-methods Please help.

      <!DOCTYPE HTML>

      <html>

      <head>

          <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

          <title>Multiple file uploader</title>

          <script>

              var totalFileLength, totalUploaded, fileCount, filesUploaded;

              var startTime;

              var speed = 0;

       

              function debug(s) {

                  var debug = document.getElementById('debug');

                  if (debug) {

                      debug.innerHTML = debug.innerHTML + '<br/>' + s;

                  }

              }

       

              function onUploadComplete(e) {

                  totalUploaded += document.getElementById('files').

                          files[filesUploaded].size;

                  filesUploaded++;

                  debug('complete ' + filesUploaded + " of " + fileCount);

                  debug('totalUploaded: ' + totalUploaded);

                  if (filesUploaded < fileCount) {

                      uploadNext();

                  } else {

                      document.getElementById('form1').reset();

                      document.getElementById('selectedFiles').innerHTML = "";

                      alert('Finished uploading file(s): ' + event.target.responseText);

                  }

              }

       

              function onFileSelect(e) {

                  var files = e.target.files; // FileList object

                  var output = [];

                  fileCount = files.length;

                  totalFileLength = 0;

                  for (var i = 0; i < fileCount; i++) {

                      var file = files[i];

                      output.push(file.name, ' (',

                              file.size, ' bytes, ',

                              file.lastModifiedDate.toLocaleDateString(), ')'

                      );

                      output.push('<br/>');

                      debug('add ' + file.size);

                      totalFileLength += file.size;

                  }

                  document.getElementById('selectedFiles').innerHTML =

                          output.join('');

                  debug('totalFileLength:' + totalFileLength);

              }

       

              function onUploadProgress(e) {

                  if (e.lengthComputable) {

                      var percentComplete = parseInt(

                              (e.loaded + totalUploaded) * 100

                              / totalFileLength);

                      var bar = document.getElementById('bar');

                      bar.style.width = percentComplete + '%';

                      bar.innerHTML = percentComplete + ' % complete';

                  } else {

                      debug('unable to compute');

                  }

              }

       

              function onUploadFailed(e) {

                  alert("Error uploading file:" + e);

              }

       

              function uploadNext() {

                  var xhr = new XMLHttpRequest();

                  var fd = new FormData();

                  var file = document.getElementById('files').files[filesUploaded];

                  fd.append('media', file);

                  //xhr.upload.addEventListener("progress", onUploadProgress, false);

                  xhr.addEventListener("load", onUploadComplete, false);

                  xhr.addEventListener("error", onUploadFailed, false);

                  debug('uploading ' + file.name);

                  xhr.open('POST', 'UploadFileServlet', true);

                  xhr.send(fd);

              }

       

              function startUpload() {

                  startTime = now();

                  totalUploaded = filesUploaded = 0;

                  uploadNext();

              }

              window.onload = function () {

                  document.getElementById('files').addEventListener(

                          'change', onFileSelect, false);

                  document.getElementById('uploadButton').

                          addEventListener('click', startUpload, false);

              }

       

              //var socket = new WebSocket("ws://localhost:9966/status_socket");

              var socket = new WebSocket("ws://" + location.hostname + ":" + location.port + "/status_socket");

              socket.onopen = function() {

                  alert("Connection established.");

              };

       

              socket.onclose = function(e) {

                  if (event.wasClean) {

                   

                  } else {

                      alert('Connection terminated');

                  }

                  alert('Code: ' + e.code + ' reason: ' + e.reason);

              };

       

              socket.onmessage = function(e) {

       

                  var endTime = now();

                  var diff = endTime - startTime;

                  var transferred = parseInt(e.data);

                  if (diff > 0 && transferred > 0) {

                      speed = transferred / diff * 100;

                  }

                  startTime = diff;

       

                  var secondsLeft = parseInt((totalFileLength - transferred - totalUploaded) / speed);

       

                  var date = new Date(null);

                  date.setSeconds(secondsLeft);

                  var timeLeft = date.toISOString().substr(11, 8);

       

                  var percentComplete = parseInt((transferred + totalUploaded) * 100 / totalFileLength);

                  var bar = document.getElementById('bar');

                  var progressBar = document.getElementById('progressBar');

                  var progressText = document.getElementById('progressText');

       

                  //bar.innerHTML = percentComplete + ' % complete' + ', time left: ' + timeLeft + ' sec';

                  //bar.style.width = percentComplete + '%';

       

                  progressBar.value = percentComplete;

                  //progressBar.innerHTML = percentComplete + ' % complete' + ', time left: ' + timeLeft + ' sec';

                  progressText.textContent = percentComplete + ' % complete' + ', time left: ' + timeLeft;

               

              };

       

              socket.onerror = function(error) {

                  alert("Error " + error.message);

              };

       

              var now = (function() {

       

                  // Returns the number of milliseconds elapsed since either the browser navigationStart event or

                  // the UNIX epoch, depending on availability.

                  // Where the browser supports 'performance' we use that as it is more accurate (microsoeconds

                  // will be returned in the fractional part) and more reliable as it does not rely on the system time.

                  // Where 'performance' is not available, we will fall back to Date().getTime().

       

                  var performance = window.performance || {};

       

                  performance.now = (function() {

                      return performance.now    ||

                              performance.webkitNow     ||

                              performance.msNow         ||

                              performance.oNow          ||

                              performance.mozNow        ||

                              function() { return new Date().getTime(); };

                  })();

       

                  return performance.now();

       

              });

       

          </script>

       

      </head>

      <body>

      <h1>Multiple file uploader</h1>

      <!--

      <div id='progressBar' style='height:20px;border:2px solid green'>

          <div id='bar'

               style='height:100%;background:#33dd33;width:0%'>

          </div>

      </div> -->

      <span id="progressText"></span>

      <progress id='progressBar' style='width:100%;height:20px;' max="100" value="0"><span>Урраааааа</span></progress>

      <form id='form1' action="UploadFileServlet"

            enctype="multipart/form-data" method="post">

          <input type="file" id="files" multiple/>

          <br/>

          <output id="selectedFiles"></output>

          <input id="uploadButton" type="button" value="Upload"/>

      </form>

      <div id='debug'

           style='height:100px;border:2px solid green;overflow:auto'>

      </div>

      </body>

      </html>

       

       

       

      import org.slf4j.Logger;

      import org.slf4j.LoggerFactory;

       

      import javax.servlet.http.HttpSession;

      import javax.websocket.EndpointConfig;

      import javax.websocket.OnMessage;

      import javax.websocket.OnOpen;

      import javax.websocket.Session;

      import javax.websocket.server.ServerEndpoint;

       

       

      @ServerEndpoint(value = "/status_socket", configurator = ServletAwareConfig.class)

      public class SocketEndpoint {

       

          private Logger logger = LoggerFactory.getLogger(this.getClass());

       

          private EndpointConfig config;

       

          @OnOpen

          public void onOpen(Session webSocketSession, EndpointConfig config) {

              this.config = config;

              HttpSession httpSession = (HttpSession)config.getUserProperties().get("httpSession");

              if (httpSession != null) {

                  httpSession.setAttribute("webSocketSession", webSocketSession);

              }

              logger.info("Received handshake");

          }

       

          @OnMessage

          public void onMessage(String message) {

       

          }

      }

       

      import javax.servlet.http.HttpSession;

      import javax.websocket.HandshakeResponse;

      import javax.websocket.server.HandshakeRequest;

      import javax.websocket.server.ServerEndpointConfig;

       

      public class ServletAwareConfig extends ServerEndpointConfig.Configurator {

       

          @Override

          public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) {

              super.modifyHandshake(config, request, response);

              HttpSession httpSession = (HttpSession)request.getHttpSession();

              config.getUserProperties().put("httpSession", httpSession);

          }

      }