JAVAEE7+WEBSOCKETS+GLASSFISH4 Create chat room _java

Source: Internet
Author: User
Tags sessions wrapper glassfish

Establish a single two-way connection between the client and the server, this means that the customer only needs to send a request to the server, then the server will be processed, the processing will be returned to the client, the client can wait for the time to continue to do other work, the whole process is asynchronous. In this series of tutorials, you will instruct users how to use the new parsing JSON API (JSR-353) in Java EE 7 and the combined use of jquery and bootstrap in the Java EE 7 container glassfish 4. This article requires readers to have some basic knowledge of HTML 5 websocket.

Effect chart

Let's take a look at the effect diagram after completing this tutorial, as follows:

Preparatory work

We are using JDK 7 and Mavn 3 to build the library, and first look at the section on Jave EE 7 in Pom.xml:

 <properties> <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir> < Project.build.sourceencoding>utf-8</project.build.sourceencoding> </properties> <dependencies > <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> &l t;version>7.0</version> <scope>provided</scope> </dependency> </dependencies> &L t;build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifa Ctid>maven-compiler-plugin</artifactid> <version>3.1</version> <configuration> ;source>1.7</source> <target>1.7</target> <compilerArguments> <endorseddirs& gt;${endorsed.dir}</endorseddirs> </compilerArguments> </configuration> </plugin> & Lt;plugin> <groupid>org.apache.mavEn.plugins</groupid> <artifactId>maven-war-plugin</artifactId> <version>2.3</version& 
   Gt <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> < /plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactid>maven-depe 
  Ndency-plugin</artifactid> <version>2.6</version> [...]  </plugin> </plugins> </build>

At the same time, in order to be able to use GlassFish 4, the following plug-ins need to be added:

plugin> 
 <groupId>org.glassfish.embedded</groupId> 
 <artifactId> maven-embedded-glassfish-plugin</artifactid> 
 <version>4.0</version> 
 < configuration> 
  <goalPrefix>embedded-glassfish</goalPrefix> 
  <app>${basedir}/target /${project.artifactid}-${project.version}.war</app> 
  <autoDelete>true</autoDelete> 
  <port>8080</port> 
  <name>${project.artifactId}</name> 
  <contextRoot> hascode</contextroot> 
 </configuration> 
 <executions> 
  <execution> 
   <goals> 
    <goal>deploy</goal> 
   </goals> 
  </execution> 
 </ Executions> 

Set the WebSocket endpoint

Let's look at the service-side WebSocket code below, and then do a further resolution:

Package com.hascode.tutorial; 
Import java.io.IOException; 
Import Java.util.logging.Level; 
 
Import Java.util.logging.Logger; 
Import javax.websocket.EncodeException; 
Import Javax.websocket.OnMessage; 
Import Javax.websocket.OnOpen; 
Import javax.websocket.Session; 
Import Javax.websocket.server.PathParam; 
 
Import Javax.websocket.server.ServerEndpoint; 
@ServerEndpoint (value = "/chat/{room}", encoders = chatmessageencoder.class, decoders = Chatmessagedecoder.class) 
 
 public class Chatendpoint {private final Logger log = Logger.getlogger (GetClass (). GetName ());  @OnOpen public void open (final sessions, @PathParam ("Room") final String room) {Log.info ("Session OpenEnd and 
  Bound to Room: "+ room); 
 Session.getuserproperties (). Put ("room", room);  @OnMessage public void OnMessage (final session session, final Chatmessage chatmessage) {String room = (string) 
  Session.getuserproperties (). Get ("room"); try {for (Session s:session.getopensessions (){if (S.isopen) && room.equals (S.getuserproperties (). Get ("Room")) {S.getbasicremote (). Sendo 
    Bject (Chatmessage); catch (IOException | 
  Encodeexception e) {log.log (level.warning, "OnMessage failed", e);  } 
 } 
}

The following code is analyzed below:

Use @ serverendpoint to define a new endpoint, where the value specifies the URL and can use pathparams parameters, as in Jax-rs.

So the value "/chat/{room}" allows the user to connect to a chat room via a URL in the following form: Ws://0.0.0.0:8080/hascode/chat/java

The value in curly braces (that is, room) can be injected as arguments in the endpoint life cycle callback method by using Javax.websocket.server.PathParam.

In addition, we're going to use a class that encodes and decodes, because we're using a dto-form class that transmits data on both the server side and the client.

When the user connects to the server for the first time, enter the room number to enter the chat room, the room number is injected as a parameter, and the value is saved in the user's property map using Session.getuserproperties.

When a chat participant sends a message to the server via a TCP connection, the loop iterates through all open sessions, each session being bound to the specified chat room, and receiving the encoded and decoded information.

If we want to send a simple text message or information in binary format, you can use Session.getbasicremote (). Sendbinary () or Session.getbasicremote (). SendText ()

Next we look at the code that represents the information delivery entity (Dto:data Transfer Object), as follows:

Package com.hascode.tutorial; 
 
Import java.util.Date; 
 
public class Chatmessage { 
 private String message; 
 Private String sender; 
 Private Date received; 
 
 Other Getter,setter Methods 
} 

Conversion of chat messages

In this application, an encoding and decoding class is written to convert between the chat information and the JSON format.

Let's take a look at the implementation of the decoding class, which converts the chat information delivered to the server to the Chatmessage entity class. Here, the Java API for JSON processing (JSR353) specification is used to convert JSON-formatted information to an entity class, where the code is as follows, where the overridden Willdecode method is returned to true by default.

 package com.hascode.tutorial; 
Import Java.io.StringReader; 
 
Import Java.util.Date; 
Import Javax.json.Json; 
Import Javax.json.JsonObject; 
Import javax.websocket.DecodeException; 
Import Javax.websocket.Decoder; 
 
Import Javax.websocket.EndpointConfig; public class Chatmessagedecoder implements decoder.text<chatmessage> {@Override public void init (final Endpoint Config config) {} @Override public void Destroy () {} @Override public chatmessage decode (final String te 
  Xtmessage) throws Decodeexception {chatmessage chatmessage = new Chatmessage (); 
  Jsonobject obj = Json.createreader (new StringReader (TextMessage)). ReadObject (); 
  Chatmessage.setmessage (obj.getstring ("message")); 
  Chatmessage.setsender (obj.getstring ("sender")); 
  Chatmessage.setreceived (New Date ()); 
 return chatmessage; 
 @Override public boolean Willdecode (final String s) {return true; } 
} 

Again, the code for the encoded class, instead of converting the Chatmessage class to JSON format, is as follows:

Package com.hascode.tutorial; 
 
Import Javax.json.Json; 
Import javax.websocket.EncodeException; 
Import Javax.websocket.Encoder; 
Import Javax.websocket.EndpointConfig; 
 
public class Chatmessageencoder implements encoder.text<chatmessage> { 
 @Override public 
 void Init (final Endpointconfig config) { 
 } 
 
 @Override public 
 Void Destroy () { 
 } 
 
 @Override public 
 String Encode (final Chatmessage chatmessage) throws Encodeexception {return 
  json.createobjectbuilder () 
    . Add (" Message ", Chatmessage.getmessage ()) 
    . Add (" Sender ", Chatmessage.getsender ()) 
    . Add (" Received ", Chatmessage.getreceived (). ToString ()). Build () 
    . ToString (); 
 } 
 

Here you can see the power of JSR-353, and simply call Json.createobjectbuilder to easily convert a Dto object to JSON.

Build simple client through bootstrap and Javacsript

Finally, we use the famous bootstrap, jquery framework, and JavaScript to design a simple client. We created the new index.html file in the Src/main/weapp directory, the code is as follows:

<! 
DOCTYPE html>  

In the above code, note the following points:

To invoke WebSocket on the JavaScript side, you can initiate the connection in the following way:Ws://ip:port/context_path/endpoint_url e.g ws://0.0.0.0:8080/ Hascode/chat/java

The way to create a WebSocket connection is simple, using the var wsocket = new WebSocket (' Ws://0.0.0.0:8080/hascode/chat/java ');

To obtain the information returned from the service side, simply set the corresponding method of obtaining the return information in the callback function Wsocket.onmessage.

Send a WebSocket message to the server using the method Wsocket.send (), where the message can be sent in either text or binary data.

The connection is closed using Wsocket.close ().

Finally, we are deploying the code through MVN package Embedded-glassfish:run, and then we can see the effect of the first part of the screenshot in this article.

The above is to use JavaEE7, WebSockets and GlassFish4 to realize the chat room, I hope to help you learn.

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.