Web application Access serial

Source: Internet
Author: User

Https://github.com/tylermenezes/SerialServe

Https://github.com/straend/SerialWebsocket

Http://www.cnblogs.com/lcchuguo/p/4007392.html

Java Applet read-write client serial Port-the ultimate article

Test environment:

Sdk:oracle JRockit for Java version 6, Java Communication for Windows 2.0

Os:windows7

Peripheral: Serial bar code scanning gun

Server:tomcat6

Look at the online and bad about the applet to visit the serial port of the article, summed up the issue of concern no outside the following 3:

1. What folder should three files (Comm.jar, javax.comm.properties, and Win32com.dll) be stored in?

2. How do I implement the code?

3. How should applets be deployed?

A On the first question, it is generally written on the Internet:

A) Place the Javax.comm.properties file in the $java_home/lib folder;

b) Place the Win32comm.dll file in the $java_home/bin folder;

c) Place the Comm.jar file in the $java_home/lib/ext folder;

Not to discuss these files should not be placed in these folders, the feasibility of the discussion is less consistent with the practice of Web applications. First you cannot predict how many clients exist, even if you know in advance that it is not possible to deploy the above 3 files on each client computer. OK, you say you can provide a manual to guide users to download files and follow the manual to deploy the above files to the specified folder. But you add the user's use of learning costs, the user is not an IT expert, it should have been completed by the developer of the task passed to the user is appropriate?

To solve the problem, the key is to test, the test applet in the implementation of the load of these files. After repeated testing, the final figure is clear:

1. The javax.comm.properties file can be discarded, because the programming method can be dynamically loaded into the applet in the serial driver, so the file does not exist does not matter.

2. The Comm.jar file is a basic serial Access class library that can be loaded by the applet execution (specified by archive, followed by a specific sample), so there is no need to deploy to the client computer beforehand.

3. The most critical is the Win32comm.dll file, the file is written in C serial (and) port driver, Java through the JNI tune the function in the file to achieve the access to the serial (and) port. So this file is indispensable. To deploy the file to the client can only be done by downloading, That is, when the applet executes, checks for the presence of the Win32comm.dll file in the specified folder, assuming that it does not exist, download the server-side Win32comm.dll file to the client's specified folder, and then dynamically load the driver. With regard to what folder the Win32comm.dll file is to be deployed to, the test finds that the file only exists in any of the folders specified by the Java.library.path system variable, which can be passed System.getproperty (" Java.library.path ") method gets. Here is the value obtained using this method in my machine:

C:/Program Files/java/jrmc-3.1.2-1.6.0/bin;.; C:/windows/system32; C:/windows; C:/Program Files/java/jrockit-r27.6.5-jre1.6.0_14/bin; C:/windows/system32; C:/windows; C:/windows/system32/wbem; c:/windows/system32/windowspowershell/v1.0/; C:/Program Files/ati Technologies/ati. ace/core-static; C:/Program Files/toshiba/bluetooth Toshiba stack/sys/; C:/Program files/securecrt/; C:/Program Files/mysql/mysql Server 5.1/bin; C:/tomcat6.0/bin; E:/software/java/jdk/ibm_sdk60/bin; C:/mingw/bin; C:/Program Files/java/jrmc-3.1.2-1.6.0/bin;

Through the above analysis, we have cleared the three file storage location, the next step is how to implement the code in detail.

Two Code implementation

A) Download the Win32comm.dll file to client:

First look at the implementation of the Code:

Private Static Final String Lib_path_suffix = "System32";

Private Static Final String dll_file = "Win32com.dll";

Try {

Get a list of paths to search when loading a library

String dirs = System. GetProperty ("Java.library.path");

String[] libs = Dirs.split (";");

String LibPath = "";

for (String lib:libs) {

if (Lib.tolowercase (). EndsWith (lib_path_suffix)) {

LibPath = Lib;

break;

}

}

File DLL = new file (LibPath, dll_file);

if (!dll.exists ()) {

URL url = new URL (super. GetCodeBase () + dll_file);

InputStream is = Url.openconnection (). getInputStream ();

FileOutputStream fos = new fileoutputstream (DLL);

byte [] buf = new byte[256]; Read cache

int len = 0;

while (len = Is.read (BUF))! =-1) {

Fos.write (buf, 0, Len);

}

Fos.flush ();

Fos.close ();

Is.close ();

System. out. println ("Create file complete [" + DLL + "].");

}

} catch (Malformedurlexception e) {

E.printstacktrace ();

} catch (IOException e) {

E.printstacktrace ();

}

The main algorithms for this code include the following:

1. The System.getproperty ("Java.library.path") method to obtain the folder string to be searched when loading the library, each folder is separated by semicolons;

2. Split the folder string into an array of strings by semicolons, and then take any one of them. Just I like to take "c:/windows/system32" folder;

3. Then instantiate a file object that contains a handle to the C:/windows/system32/win32comm.dll file. Check whether the file exists, assuming that there is no matter what processing, otherwise download processing;

4. Assuming you need to download the file, first obtain the server-side root URL object through the GetCodeBase () method. Then construct a URL object pointing to the server-side Win32comm.dll file;

5. Get the InputStream stream ready to read via the URL of the OpenConnection (). getInputStream () method.

6. Instantiate a FileOutputStream object in client and write the output stream to the client's file (C:/windows/system32/win32comm.dll), complete the file download. In fact, the download of the file is through the HTTP protocol, that is, httpclient. So the server side needs Tomcat or other webserver software.

b) Barcode Reading

The main implementation of the applet 3 methods: Init, start and destroy method. First look at the Init method:

Private String drivername = "Com.sun.comm.Win32Driver";

Public void init () {

Try {

System. loadLibrary ("win32com");

Commdriver Driver = (commdriver) Class. forname (drivername). newinstance ();

Driver.initialize ();

} catch (Exception e) {

System. err. println (e);

}

}

The Init method runs once and only once when the applet is loaded. Therefore, the Init method is suitable for loading and initializing the driver, that is, loading the Win32comm.dll file.

Barcode scanning Device Unlike a modem, a modem uses a "secret step" method of communication, which is the request-response mode. and barcode scanning equipment is event-driven, only after scanning the barcode, ability to read the serial port data, so use the request-response mode is definitely not. To solve the problem, the applet must implement the Serialporteventlistener interface to run a specific method when there is data arriving. There is also a need to start a thread to wait for the data to arrive. So the signature of the Applet class is as follows:

Public class Serialportapplet extends japplet implements Runnable,

Serialporteventlistener {

Public void run () {

}

Public void serialevent (serialportevent event) {

}

}

The Serialevent (Serialportevent event) method is the interface method that needs to be implemented, and the code in the method is run when the serial port has data to arrive.

The Start method runs after the Init method runs, and the Start method can be run multiple times throughout the applet's lifetime. So the Start method can be used to find the available ports, open the port, set the port parameters, wait for the data to arrive, and so on, the code such as the following see:

Private Commportidentifier Portid;

Private StringBuilder barcode = new StringBuilder ();

Private InputStream is;

Private Boolean over = false; Flag to exit Thread

Private SerialPort SerialPort;

static {

System. Setsecuritymanager (null); //Disable Security Manager (must write)

}

Public void Start () {

Enumeration ports = Commportidentifier. getportidentifiers ();

while (Ports.hasmoreelements ()) {

Portid = (commportidentifier) ports.nextelement ();

if (Portid.getporttype () = = Commportidentifier. port_serial) {//IS serial port

if (Portid.getname (). Equals ("COM1")) {

break;

}

}

}

Try {

SerialPort = (serialPort) portid.open ("App1", 2000); Open port

is = Serialport.getinputstream ();

Serialport.addeventlistener (this); Register Listener

Serialport.notifyondataavailable (true); Notify when data is reached

Serialport.setserialportparams (9600, SerialPort. Databits_8, SerialPort. stopbits_1, SerialPort. Parity_none); Set Port parameters

} catch (Portinuseexception e) {

System. err. println (e);

} catch (IOException e) {

System. err. println (e);

} catch (Toomanylistenersexception e) {

System. err. println (e);

} catch (Unsupportedcommoperationexception e) {

System. err. println (e);

}

Start thread

Thread T = new thread (this);

T.start ();

Try {

T.join ();//wait for thread to end

} catch (Interruptedexception e) {

}

System. out. println ("barcode[" + barcode + "]");

}

The implementation of the thread interface and the implementation code for the listener interface are seen below:

Public void Run () {

while (!over) {

}

Try {

if (IS! = null) {

Is.close ();

}

if (SerialPort! = null) {

Serialport.close ();

}

} catch (IOException e) {

System. out. println (e);

}

}

Public void serialevent (serialportevent event) {

Switch (Event.geteventtype ()) {

Case Serialportevent. data_available://Run when data arrives

Try {

while (true) {

int b = is.read (); Assuming that the data is not being read will clog

if (b = = Ten | | b = = 13) {//Assuming that a carriage return or line break means that the read is complete

over = true;

break;

} Else {

Barcode.append ( new String (new byte[] {(byte) b}));

}

}

} catch (IOException e) {

System. err. println (e);

}

}

}

The Destroy method runs and runs once when the applet is destroyed, so you can write the code for the resource release in the method, such as the following:

Public void Destroy () {

Try {

if (IS! = null) {

Is.close ();

}

if (SerialPort! = null) {

Serialport.close ();

}

} catch (IOException e) {

System. out. println (e);

}

}

c) HTML page (index.html)

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">

<meta http-equiv= "Content-type" content= "text/html; charset=gb2312 "/>

<title></title>

<body>

<!--"Converted_applet"-

<!--HTML CONVERTER--

<object classid= "Clsid:8ad9c840-044e-11d1-b3e9-00805f499d93"

WIDTH = "HEIGHT" = "codebase=" http://java.sun.com/update/1.6.0/jinstall-6u17-windows-i586.cab#Version= 6,0,0,4 ">

<param NAME = CODE VALUE = "Org.oakman.applets.SerialPortApplet.class" >

<param NAME = CODEBASE VALUE = "." >

<param NAME = ARCHIVE VALUE = "Comm.jar, Serial_port.jar" >

<param name= "type" value= "application/x-java-applet;version=1.6" >

<param name= "scriptable" value= "false" >

<COMMENT>

<embed type= "application/x-java-applet;version=1.6" CODE = "Org.oakman.applets.SerialPortApplet.class" CODEBASE = "." ARCHIVE = "Comm.jar,serial_port.jar" WIDTH = "HEIGHT =" "Scriptable=false pluginspage=" Http://java.sun.com/prod Ucts/plugin/index.html#download "><NOEMBED>

</NOEMBED>

</EMBED>

</COMMENT>

</OBJECT>

<!--"End_converted_applet"-

</body>

The more important is the archive, the ability to use all of the Jar class libraries used by the applet are set in this parameter, multiple jar files are separated by commas. Assuming that the client does not have a JRE installed, the user is first asked to download the JRE, which normally takes about 10 minutes to download.

After the above steps, we are finished with all the code that needs to be implemented. Package all Java code into a jar file, and then deploy it to TOMCAT6 with the HTML file, start it all right, and then be happy to open the browser, enter the URL, and the eyes full of anticipation waiting for an exciting scene. Just ..., the error! It's frustrating! Error prompt without access permission!! Depressed in ...

Three Deployment

Java claims to be the safest, so applets as small applications that can spread freely on the web are certainly more secure. So, by default, applets can only be executed in the JVM sandbox. You cannot access the client's resources, including file system read/write, network sockets, etc. So the mistake of the above is, of course, proof that Java is really safe.

To get out of the sandbox, we have to sign the applet:

1. Create the key:

Use the following command for key creation, where the RSA algorithm is used instead of the Java default DSA algorithm

Keytool-genkey-alias Oakman-keyalg RSA

Execution will require you to enter the KeyStore password and require you to enter information such as name, organization, and location. After filling out the key will be generated (key file in the user folder, looking for. keystore files).

2. Order the signing certificate from the CA:

In order to order a signed certificate from a CA, you need to export the certificate signing request (CSR file) from the KeyStore. Use such as the following command

Keytool-certreq-alias Oakman-file OAKMAN.CSR

The command generates a OAKMAN.CSR file in the current folder, and you can then apply for your certificate (a more common CA has VeriSign) with this file, as well as proof of your identity and a number of K's RMB to the CA. Assuming a successful application, the CA will give you a BASE64 encoding certificate, you can import it into the KeyStore to sign your own applets, import commands such as the following:

Keytool-import-alias Oakman-file Oakman.cer

Oakman.cer is the certificate that CA gives you.

3. Sign the applet's jar file:

Having imported the CA's certificate into the KeyStore, you can sign your own applets (and, of course, package them first), using the following command, for example:

Jarsigner Serial_port.jar Oakman

Jarsigner Comm.jar Oakman

All the jar files used by the applet are signed.

With these steps, our applets are able to get out of the sandbox and access the client's resources, including file systems, peripherals, and network sockets. The barcode scanner is connected to the serial port of my Notebook, find a book, the bar code on the book Sweep, beep!! The scan succeeds, and then a bunch of numbers appear in the Java console, ok! Finally done. (Note: Because my notebook does not have a serial port, so through the USB to the serial port to simulate the serial port, it may be because of driver reasons, assuming that the situation is not closed the Internet Explorer, the operating system must crash, only can manually restart the operating system. )

Of course, as a test, we do not need to spend a number of K to the CA to apply for a certificate, so we can omit step 2. The jar file is signed directly after the KeyStore is generated.

Four Deployment folder

Here is the deployment folder for the application in Tomcat on my machine:

Pay

|--Web-inf

|--Web

|--Comm.jar

|--Serial_port.jar

|--index.html

Web application Access serial

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.