Java Reality WebSocket
--Reprint
Directory
- Server-side implementation (TOMCAT)
- Client implementation (Java-websocket)
- Client implementations (JavaScript native API)
1. Server-side implementation (TOMCAT)
Java implementation of the WebSocket, on the server side is through Tomcat embedded support, we need to develop an inherited websocketservlet servlet can be, and ordinary httpservlet is not much different.
1). Java Environment:
- Java:jdk 1.6.0_45, Server VM 64bit
- maven:3.0.5
- tomcat:7.0.39.0
~ D:\workspace\java>java-versionjava Version "1.6.0_45" Java (TM) SE Runtime Environment (build 1.6.0_45-b06) Java HotSpot (TM) 64-bit Server VM (build 20.45-b01, Mixed mode) ~ D:\workspace\java>mvn-versionapache Maven 3.0.5 (r01de1472 4cdef164cd33c7c8c2fe155faf9602da; 2013-02-19 21:51:28+0800) Maven home:d:\toolkit\maven3\bin\. Java version:1.6.0_45, Vendor:sun Microsystems Inc.java Home:d:\toolkit\java\jdk6\jredefault locale:zh_cn, platform en Coding:gbkos Name: "Windows 7", Version: "6.1", Arch: "AMD64", Family: "Windows" ~ d:\toolkit\tomcat7\bin>catalina.bat Versionusing catalina_base: "D:\toolkit\tomcat7" Using Catalina_home: "D:\TOOLKIT\TOMCAT7" Using Catalina_tmpdir: "D:\ Toolkit\tomcat7\temp "Using jre_home:" D:\toolkit\java\jdk6 "Using CLASSPATH:" D:\toolkit\tomcat7\bin\bootstrap . Jar;d:\toolkit\tomcat7\bin\tomcat-juli.jar "Server version:apache tomcat/7.0.39server Built:mar 22 2013 12:37:24server number:7.0.39.0os name:windows 7OS Version:6.1ARCHITECTURE:AMD64JVM VERSION:1.6.0_45-B06JVM Vendor:sun Microsystems Inc.
2). MAVEN builds a simple WebApp project.
~ D:\WORKSPACE\JAVA>MVN Archetype:generate-dgroupid=org.conan.websocket-dartifactid=websocketserver- Darchetypeartifactid=maven-archetype-webapp[info]------------------------------------------------------------- ---------------[INFO] Using following parameters for creating project from the old (1.x) archetype:maven-archetype-webapp:1. 0[info]----------------------------------------------------------------------------[INFO] Parameter:groupid, Value:org.conan.websocket[info] Parameter:packagename, Value:org.conan.websocket[info] parameter:package, Value: Org.conan.websocket[info] Parameter:artifactid, Value:websocketserver[info] Parameter:basedir, value:d:\workspace\ Java[info] parameter:version, Value:1.0-snapshot[info] project created from the old (1.x) archetype in Dir:d:\workspace\jav A\websocketserver[info]------------------------------------------------------------------------[INFO] BUILD Success[info]------------------------------------------------------------------------[info] Total Time:1:42.200s[info] finished at:tue 13:57:05 CST 2013[info] Final Memory:9m/179m[info]---------- --------------------------------------------------------------
3). Configure the project directory
~ D:\workspace\java>cd websocketServer~ D:\workspace\java\websocketServer>mkdir src\main\java~ D:\workspace\java\websocketServer>rm src\main\webapp\index.jsp
Projects that are imported into eclipse
4). Edit the Pom.xml configuration file to increase Tomcat dependency
~ VI pom.xml<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>org.conan.websocket</groupId>< artifactid>websocketserver</artifactid><packaging>war</packaging><version>1.0- Snapshot</version><name>websocketserver Maven webapp</name><url>http://maven.apache.org </url><dependencies><dependency><groupId>org.apache.tomcat</groupId>< artifactid>tomcat-catalina</artifactid><version>7.0.27</version><scope>provided< /scope></dependency><dependency><groupid>org.apache.tomcat</groupid><artifactid >tomcat-coyote</artifactId><version>7.0.39</version><scope>provided</scope> </dependency></dependencies≫<build><finalname>websocketserver</finalname></build></project>
Download and install the class library
~ D:\workspace\java\websocketServer>mvn clean install
5). Create Demoservlet, server-side run class
~ VI src/main/java/org/conan/websocket/demoservlet.javapackage org.conan.websocket;import java.io.IOException; Import Java.nio.bytebuffer;import Java.nio.charbuffer;import Java.util.arraylist;import Javax.servlet.http.httpservletrequest;import Org.apache.catalina.websocket.messageinbound;import Org.apache.catalina.websocket.streaminbound;import Org.apache.catalina.websocket.websocketservlet;import Org.apache.catalina.websocket.wsoutbound;public class Demoservlet extends Websocketservlet {private static final long Serialversionuid = -4853540828121130946l; private static ArrayList mmilist = new ArrayList (); @Override protected Streaminbound createwebsocketinbound (String str, httpservletrequest request) {return new My Messageinbound (); } private class Mymessageinbound extends Messageinbound {wsoutbound myoutbound; @Override public void OnOpen (Wsoutbound outbound) {try {System.out.println ("Open Client ."); This.myoutbound = outbound; Mmilist.add (this); Outbound.writetextmessage (Charbuffer.wrap ("hello!")); } catch (IOException e) {e.printstacktrace (); }} @Override public void onClose (int status) {System.out.println ("Close Client."); Mmilist.remove (this); } @Override public void Ontextmessage (Charbuffer cb) throws IOException {System.out.println ("Acc EPT Message: "+ CB"; for (Mymessageinbound mmib:mmilist) {Charbuffer buffer = charbuffer.wrap (CB); Mmib.myoutbound.writeTextMessage (buffer); Mmib.myoutbound.flush (); }} @Override public void onbinarymessage (Bytebuffer bb) throws IOException {}}}
6). Modify the Web. xml file
~ vi src/main/webapp/WEB-INF/web.xml<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"><display-name>Archetype Created Web Application</display-name><servlet><servlet-name>wsServlet</servlet-name><servlet-class>org.conan.websocket.DemoServlet</servlet-class></servlet><servlet-mapping><servlet-name>wsServlet</servlet-name><url-pattern>/wsServlet</url-pattern></servlet-mapping></web-app>
7). Compile, package, deploy to Tomcat
~ D:\workspace\java\websocketServer>mvn clean install~ D:\workspace\java\websocketServer>cp target\websocketServer.war D:\toolkit\tomcat7\webapps
Start Tomcat
~ D:\toolkit\tomcat7>bin\catalina.bat runusing catalina_base: "D:\toolkit\tomcat7" Using catalina_home: "D:\ Toolkit\tomcat7 "Using Catalina_tmpdir:" D:\toolkit\tomcat7\temp "Using Jre_home:" D:\toolkit\java\jdk6 "Using Classpa TH: "D:\toolkit\tomcat7\bin\bootstrap.jar;d:\toolkit\tomcat7\bin\tomcat-juli.jar" 2013-8-20 14:43:29 Org.apache.catalina.core.AprLifecycleListener init info: The APR based Apache Tomcat Native Library which allows optimal perf Ormance in production environments is not found on the java.library.path:d:\toolkit\java\jdk6\bin; C:\Windows\Sun\Java\bin; C:\Windows\system32; C:\windows;d:\toolkitrtools\bin;d:\toolkit\rtools\gcc-4.6.3\bin; C:\Program Files (x86) \common Files\netsarang; C:\Windows\system32; C:\Windows; C:\Windows\System32\Wbem; C:\Windows\System32\WindowsPowerShell\v1.0\;D: \toolkit\git\cmd;d:\toolkit\git\bin; C:\Program Files (x86) \microsoft SQL server\100\tools\binn\; C:\Program Files\Microsoft SQL Server\100\tools\binn\; C:\Program Files\Microsoft SQL Server\100\dts\binn\;c:\program Files (x86) \common Files\ulead systems\mpeg; C:\Program Files (x86) \quicktime\qtsystem\;D: \toolkit\miktex\miktex\bin\x64\;D: \toolkit\sshclient;d:\toolkit\ Ant19\bin;d:\toolkit\eclipse;d:\toolkit\gradle15\bin;d:\toolkit\java\jdk6\bin;d:\toolkit\maven3\bin;d:\toolkit \mysql56\bin;d:\toolkit\python27;d:\toolkit\putty; C:Program files\r\r-3.0.1\bin\x64;d:\toolkit\mongodb243\bin;d:\toolkit\php54;d:\toolkit\nginx140;d:\toolkit\ Nodejs;d:\toolkit\npm12\bin;d:\toolkit\java\jdk6\jre\bin\server;. 2013-8-20 14:43:30 org.apache.coyote.AbstractProtocol init info: Initializing protocolhandler ["http-bio-8080"] 2013-8-20 14:43:30 org.apache.coyote.AbstractProtocol init info: Initializing protocolhandler ["ajp-bio-8009"]2013-8-20 14:43:30 Org.apache.catalina.startup.Catalina Load Info: Initialization processed in 1409 ms2013-8-20 14:43:30 Org.apache.catalina.core.StandardService startinternal Info: Starting service catalina2013-8-20 14:43:30 Org.apache.catalina.core.StandardEngine StartiNternal Info: Starting Servlet engine:apache tomcat/7.0.392013-8-20 14:43:30 org.apache.catalina.startup.HostConfig Deploywar Info: Deploying Web application Archive D:\toolkit\tomcat7\webapps\websocketServer.war2013-8-20 14:43:30 Org.apache.catalina.startup.HostConfig deploydirectory Info: Deploying Web application Directory D:\toolkit\tomcat7\ webapps\docs2013-8-20 14:43:30 org.apache.catalina.startup.HostConfig deploydirectory Info: Deploying Web Application Directory D:\toolkit\tomcat7\webapps\examples2013-8-20 14:43:31 Org.apache.catalina.startup.HostConfig Deploydirectory Info: Deploying Web application directory D:\toolkit\tomcat7\webapps\host-manager2013-8-20 14:43:31 Org.apache.catalina.startup.HostConfig deploydirectory Info: Deploying Web application Directory D:\toolkit\tomcat7\ webapps\manager2013-8-20 14:43:31 org.apache.catalina.startup.HostConfig deploydirectory info: Deploying Web Application directory D:\toolkit\tomcat7\webapps\ROOT2013-8-20 14:43:31 Org.apache.coyote.AbstractProtocol starT info: Starting Protocolhandler ["http-bio-8080"]2013-8-20 14:43:31 org.apache.coyote.AbstractProtocol Start info: Starting Protocolhandler ["ajp-bio-8009"]2013-8-20 14:43:31 Org.apache.catalina.startup.Catalina start info: Server Startup in 996 MS
WebSocket's service address:
Ws://localhost:8080/websocketserver/wsservlet
2. Client implementation (Java-websocket)
The WebSocket client is implemented in Java, which is described here as "Java-websocket". In addition, I found that Java7 has natively supported WebSocket, "JSR 365, Java API for WebSocket" (it seems to be beginning to learn java7 and java8, I have been stuck in the java6 era for 3-4 years.) )
Now we use "Java-websocket"
1). Modify the Pom.xml file to increase the jetty WebSocket dependent library
~ vi pom.xml<dependency><groupId>org.java-websocket</groupId><artifactId>Java-WebSocket</artifactId><version>1.3.0</version></dependency>
Download Dependent libraries
~ D:\workspace\java\websocketServer>mvn clean install
2). new file, Chatclient.java
~ VI src/main/java/org/conan/websocket/chatclient.javapackage org.conan.websocket;import java.awt.Container;import Java.awt.gridlayout;import Java.awt.event.actionevent;import Java.awt.event.actionlistener;import Java.awt.event.windowevent;import Java.net.uri;import Java.net.urisyntaxexception;import Javax.swing.JButton; Import Javax.swing.jcombobox;import javax.swing.jframe;import Javax.swing.jscrollpane;import Javax.swing.JTextArea ; Import Javax.swing.jtextfield;import Org.java_websocket. Websocketimpl;import Org.java_websocket.client.websocketclient;import Org.java_websocket.drafts.draft;import Org.java_websocket.drafts.draft_10;import Org.java_websocket.drafts.draft_17;import Org.java_ Websocket.drafts.draft_75;import Org.java_websocket.drafts.draft_76;import Org.java_ Websocket.handshake.serverhandshake;public class ChatClient extends JFrame implements ActionListener {private static F inal long serialversionuid = -6056260699202978657l; Private final JTextField Urifield; Private final JButton Connect; Private final JButton close; Private Final JTextArea ta; Private final JTextField Chatfield; Private final JComboBox draft; Private Websocketclient cc; Public ChatClient (String defaultlocation) {super ("WebSocket Chat Client"); Container C = Getcontentpane (); GridLayout layout = new GridLayout (); Layout.setcolumns (1); Layout.setrows (6); C.setlayout (layout); Draft[] Drafts = {new Draft_17 (), New Draft_10 (), New draft_76 (), New draft_75 ()}; Draft = new JComboBox (drafts); C.add (draft); Urifield = new JTextField (); Urifield.settext (defaultlocation); C.add (Urifield); Connect = new JButton ("Connect"); Connect.addactionlistener (this); C.add (connect); Close = new JButton ("close"); Close.addactionlistener (this); Close.setenabled (FALSE); C.add (Close); JScrollPane scroll = new JscrolLpane (); Ta = new JTextArea (); Scroll.setviewportview (TA); C.add (scroll); Chatfield = new JTextField (); Chatfield.settext (""); Chatfield.addactionlistener (this); C.add (Chatfield); Java.awt.Dimension d = new Java.awt.Dimension (300, 400); Setpreferredsize (d); SetSize (d); Addwindowlistener (New Java.awt.event.WindowAdapter () {@Override public void windowclosing (Windowe Vent e) {if (cc! = null) {cc.close (); } dispose (); } } ); Setlocationrelativeto (NULL); SetVisible (TRUE); public void actionperformed (ActionEvent e) {if (e.getsource () = = Chatfield) {if (cc! = null) {Cc.send (Chatfield.gettext ()); Chatfield.settext (""); Chatfield.requestfocus (); }} else if (e.getsource () = = ConNect) {try {//cc = new ChatClient (New URI (Urifield.gettext ()), area, (Draft) Draft.getsele Cteditem ()); CC = new Websocketclient (New URI (Urifield.gettext ()), (Draft) Draft.getselecteditem ()) {@Override public void OnMessage (String message) {Ta.append ("Got:" + message + "\ n"); Ta.setcaretposition (Ta.getdocument (). GetLength ()); } @Override public void OnOpen (Serverhandshake handshake) { Ta.append ("Connected to Chatserver:" + geturi () + "\ n"); Ta.setcaretposition (Ta.getdocument (). GetLength ()); } @Override public void onClose (int code, String reason, Boolean remote) { Ta.append ("You had been disconnected from:" + geturi () + "; Code: "+ code +" "+ Reason + "\ n"); Ta.setcaretposition (Ta.getdocument (). GetLength ()); Connect.setenabled (TRUE); Urifield.seteditable (TRUE); Draft.seteditable (TRUE); Close.setenabled (FALSE); } @Override public void OnError (Exception ex) {ta.append ( "Exception occured ... \ n" + ex + "\ n"); Ta.setcaretposition (Ta.getdocument (). GetLength ()); Ex.printstacktrace (); Connect.setenabled (TRUE); Urifield.seteditable (TRUE); Draft.seteditable (TRUE); Close.setenabled (FALSE); } }; Close.setenabled (TRUE); Connect.setenabled (FALSE); Urifield.seteditable (FALSE); Draft.seteDitable (FALSE); Cc.connect (); } catch (URISyntaxException ex) {Ta.append (Urifield.gettext () + "is not a valid WebSocket uri\n"); }} else if (e.getsource () = = close) {cc.close (); }} public static void Main (string[] args) {websocketimpl.debug = true; String location; if (args.length! = 0) {location = args[0]; SYSTEM.OUT.PRINTLN ("Default server URL specified: \ '" + location + "\ '"); } else {location = "ws://localhost:8887"; SYSTEM.OUT.PRINTLN ("Default server URL not specified:defaulting to \ '" + location + "\ '"); } new ChatClient (location); }}
To run the program:
This will launch a Java GUI interface. Enter the address of the WebSocket service: Ws://localhost:8080/websocketserver/wsservlet
To view a conversation between the Java client and the HTML client, in the Java client, enter "Hello, little Friend".
We found in the HTML client, the same "Hello, little friend" message record.
In this way, we have implemented the Java WebSocket client program in the JAVA6 environment.
3. Client implementation (JavaScript native API)
Write a plain HTML web page that implements a call to the WebSocket service through the native websocketapi of the browser.
~ vi D:\workspace\javascript\tomcatClient.html<!DOCTYPE html>
Files just written by the browser: file:///D:/workspace/javascript/tomcatClient.html
Open two windows:
In the right window, enter "I am BBB" and click Send. Left, right this, and background log, while adding "I am BBB".
Originally in the browser above, realize the chat function is so simple!!
Java Reality WebSocket