简体   繁体   中英

How to read data in JavaScript from a Java server?

I'm running a simple server that show time, and when someone connects to it using telnet\\putty he can see the time.

I need to write a code in JavaScript that reads the data from the server. how do I do this ?

this is the server code

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Calendar;




class ClientThread extends Thread {

   private final Socket _socket;

   public ClientThread( Socket socket ) {
      System.out.println( "New client" );
      _socket = socket;
      setDaemon( true );
      start();
   }

   @Override
   public void run() {
      try(
         final OutputStream outputFromServer = _socket.getOutputStream();
         final PrintWriter serverPrintOut = new PrintWriter(
            new OutputStreamWriter( outputFromServer, "utf-8" ), true ))
      {
         serverPrintOut.println( "Welcome to time server" );
         for(;;) {
            final long elapsed = System.currentTimeMillis() - MyServer.StartTime;
            serverPrintOut.println( elapsed );
            Thread.sleep( 1000L );
         }
      }
      catch( final InterruptedException ex) {/**/}
      catch( final IOException e ) {
         e.printStackTrace();
      }
   }
}

public class MyServer {

   static Calendar startTime = Calendar.getInstance();
   static long StartTime = System.currentTimeMillis();



   public static void main( String[] args ) throws IOException {
      try( ServerSocket serverSocket = new ServerSocket( 9991 )) {
         for(;;) {
            new ClientThread( serverSocket.accept());
         }
      }
   }
}

this is what I have in JavaScript

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <%--<script type="text/javascript" src="jsocket.js"></script>--%>
    <%--<script type='text/javascript'>--%>
        <%--// Host we are connecting to--%>
        <%--var host = '10.0.0.82';--%>
        <%--// Port we are connecting on--%>
        <%--var port = 9991;--%>

        <%--var socket = new JSocket();--%>

        <%--// When the socket is added the to document--%>
        <%--socket.onReady = function(){--%>
            <%--socket.connect(host, port);--%>
        <%--}--%>

        <%--// Connection attempt finished--%>
        <%--socket.onConnect = function(success, msg){--%>
            <%--if(success){--%>
                <%--// Send something to the socket--%>
                <%--socket.write('Hello world');--%>
            <%--}else{--%>
                <%--alert('Connection to the server could not be estabilished: ' + msg);--%>
            <%--}--%>
        <%--}--%>
        <%--socket.onData = function(data){--%>
            <%--alert('Received from socket: '+data);--%>
        <%--}--%>

        <%--// Setup our socket in the div with the id="socket"--%>
        <%--socket.setup('mySocket');--%>
    <%--</script>--%>
    <script src="socket.io.js"></script>
    <script>
//        var socket = io('http://10.0.0.82:9991');
//        socket.on('connect', function(){});
//        socket.on('event', function(data){});
//        socket.on('disconnect', function(){});


        var socket = io('10.0.0.82:9991');
        socket.on('news', function (data) {
            console.log(data);
            socket.emit('my other event', { my: 'data' });
        });
    </script>
</head>
<body>

</body>
</html>

but when I run the JavaScript code I get error "Invalid http resonse" which I understand why(the server is not http) - but how do I overcome this ? what will be fast and easy - change the JavaScript or make the server http ?

  • I do want to add that the final code will be handling 30 types of data (in the server) - all kind of sensor reading.

tl;dr

According to this Answer , here is the JavaScript for parsing a count of milliseconds since the epoch reference of 1970-01-01T00:00Z.

var date = new Date( millisecondsSinceEpochReference );

Additional suggestions

In addition to the JavaScript code, I can offer some major suggestions: Java Servlets, java.time classes, and ISO 8601 formats.

Java Servlet

There is no need to re-invent a web server. Java Servlet technology was invented to make this kind of work very simple.

Write a simple servlet app that returns your desired string. Takes just a few lines of code.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

@WebServlet ( "/now" )
public class NowServlet extends HttpServlet {

    public void doGet ( HttpServletRequest req , HttpServletResponse res )
        throws ServletException, IOException {

        res.setContentType( "text/plain" );
        PrintWriter out = res.getWriter();

        Instant instant = Instant.now();
        String output = instant.toString();

        out.println( output );
    }
}

Then run your servlet on any Servlet-compliant server (a web container ) such as Apache Tomcat or Eclipse Jetty .

If you want to, you could get fancy by making a RESTful web service.

java.time

Your Java backend is using terrible old date-time classes that were supplanted years ago by the modern java.time classes.

If you insist on tracking a moment as a count from an epoch reference , here is code to get a count of milliseconds since 1970-01-01T00:00Z .

Instant.now().toEpochMilli() 

But I suggest you exchange text rather than this mere integer. Read on.

ISO 8601

When exchanging date-time values as text, use standard ISO 8601 formatting. These formats are practical and useful, designed to avoid ambiguity, and are easy to parse by machine as well as easy to read by humans across cultures.

The java.time classes use these standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.

For a value in UTC , use Instant class.

String output = Instant.now().toString() ;

2018-11-13T02:16:19.422836Z

You can parse such a string back into an object.

Instant instant = Instant.parse( "2018-11-13T02:16:19.422836Z" ) ;  

If your destination is restricted to milliseconds instead of java.time resolution of nanoseconds , truncate.

String output = 
    Instant
    .now()
    .truncatedTo( ChronoUnit.MILLIS )
    .toString() 
;

2018-11-13T02:18:05.333Z

You may want to exchange the value as seen in the wall-clock time used by the people of a particular region (a time zone ). But generally speaking, the best practice is to exchange moments in UTC .

For a time zone, use the ZonedDateTime class. The toString method on this class wisely extends the ISO 8601 standard by appending the name of the time zone in square brackets.

String output = 
    ZonedDateTime                          // Represent a moment as seen through the wall-clock time used by the people of a particular region (a time zone).
    .now(                                  // Capture the current moment.
        ZoneId.of( "America/Montreal" )    // Always specify proper zone name in `Continent/Region` format, never 2-4 letter pseudo-zones such as PST, EST, CEST, or IST.
    )                                      // Returns a `ZonedDateTime` object.
    .toString()                            // Generates text in ISO 8601 format extended to append the name of zone in square brackets.

2018-11-12T21:27:54.595139-05:00[America/Montreal]

You can parse such a string back into an object.

ZonedDateTime zdt = ZonedDateTime.parse( "2018-11-12T21:27:54.595139-05:00[America/Montreal]" ) ;

If need be, truncate as seen above.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat .

The Joda-Time project, now in maintenance mode , advises migration to the java.time classes.

To learn more, see the Oracle Tutorial . And search Stack Overflow for many examples and explanations. Specification is JSR 310 .

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM