简体   繁体   English

如何从Java服务器读取JavaScript中的数据?

[英]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. 我正在运行一个显示时间的简单服务器,当有人使用telnet \\ putty连接到该服务器时,他可以看到时间。

I need to write a code in JavaScript that reads the data from the server. 我需要用JavaScript编写一个从服务器读取数据的代码。 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 这就是我在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 ? 但是,当我运行JavaScript代码时,出现错误“无效的http共振”,我理解为什么(服务器不是http)-但是我该如何克服呢? what will be fast and easy - change the JavaScript or make the server http ? 什么是快速简便的方法-更改JavaScript或将服务器设置为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. 我确实想补充一点,最终代码将处理30种类型的数据(在服务器中)-各种传感器读取。

tl;dr TL;博士

According to this Answer , here is the JavaScript for parsing a count of milliseconds since the epoch reference of 1970-01-01T00:00Z. 根据此Answer ,这是JavaScript,用于解析自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. 除了JavaScript代码之外,我还可以提供一些主要建议:Java Servlet, java.time类和ISO 8601格式。

Java Servlet Java Servlet

There is no need to re-invent a web server. 无需重新发明Web服务器。 Java Servlet technology was invented to make this kind of work very simple. 发明Java Servlet技术是为了使这种工作非常简单。

Write a simple servlet app that returns your desired string. 编写一个简单的servlet应用程序,以返回所需的字符串。 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 . 然后在任何与Servlet兼容的服务器( Web容器 )上运行servlet,例如Apache TomcatEclipse Jetty

If you want to, you could get fancy by making a RESTful web service. 如果愿意,可以通过制作RESTful Web服务来实现。

java.time java.time

Your Java backend is using terrible old date-time classes that were supplanted years ago by the modern java.time classes. 您的Java后端使用的是可怕的旧日期时间类,而现代的java.time类已在几年前取代了该类

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 . 如果您坚持要从纪元参考中跟踪时刻,那么这里的代码将获取自1970-01-01T00:00Z以来的毫秒数。

Instant.now().toEpochMilli() 

But I suggest you exchange text rather than this mere integer. 但是我建议您交换文本,而不是仅仅交换整数。 Read on. 继续阅读。

ISO 8601 ISO 8601

When exchanging date-time values as text, use standard ISO 8601 formatting. 在将日期时间值作为文本交换时,请使用标准的ISO 8601格式。 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. 解析/生成字符串时, java.time类默认使用这些标准格式。 So no need to specify a formatting pattern. 因此,无需指定格式化模式。

For a value in UTC , use Instant class. 对于UTC中的值,请使用Instant类。

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

2018-11-13T02:16:19.422836Z 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. 如果将目的地限制为毫秒,而不是java.time分辨率( 纳秒) ,请截断。

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

2018-11-13T02:18:05.333Z 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 . 但总的来说,最佳实践是在UTC中交换时间。

For a time zone, use the ZonedDateTime class. 对于时区,请使用ZonedDateTime类。 The toString method on this class wisely extends the ISO 8601 standard by appending the name of the time zone in square brackets. 此类的toString方法通过将时区的名称附加在方括号中来明智地扩展了ISO 8601标准。

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] 2018-11-12T21:27:54.595139-05:00 [美国/蒙特利尔]

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 关于java.time

The java.time framework is built into Java 8 and later. java.time框架内置于Java 8及更高版本中。 These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat . 这些类取代了麻烦的旧的旧式日期时间类,例如java.util.DateCalendarSimpleDateFormat

The Joda-Time project, now in maintenance mode , advises migration to the java.time classes. 现在处于维护模式Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial . 要了解更多信息,请参见Oracle教程 And search Stack Overflow for many examples and explanations. 并在Stack Overflow中搜索许多示例和说明。 Specification is JSR 310 . 规格为JSR 310

You may exchange java.time objects directly with your database. 您可以直接与数据库交换java.time对象。 Use a JDBC driver compliant with JDBC 4.2 or later. 使用与JDBC 4.2或更高版本兼容的JDBC驱动程序 No need for strings, no need for java.sql.* classes. 不需要字符串,不需要java.sql.*类。

Where to obtain the java.time classes? 在哪里获取java.time类?

The ThreeTen-Extra project extends java.time with additional classes. ThreeTen-Extra项目使用其他类扩展了java.time。 This project is a proving ground for possible future additions to java.time. 该项目为将来可能在java.time中添加内容提供了一个试验场。 You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more . 您可以在这里找到一些有用的类,比如IntervalYearWeekYearQuarter ,和更多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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