Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to build chat rooms with JavaEE7, Websockets and GlassFish4 (1)

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Today, I'm going to talk to you about how to use JavaEE7, Websockets and GlassFish4 to create chat rooms (1). Many people may not know much about it. In order to make you understand better, the editor summarized the following. I hope you can get something from this article.

Java EE 7 has been officially released this year, with a lot of new features and features, such as new or updated JSR standards. The one that has attracted particular attention is Websockets. One of its benefits is that it reduces unnecessary network traffic. It is mainly used to 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 process it, and then return it to the client, and the client can wait for this time to continue to do other work, the whole process is asynchronous. In this series of tutorials, you will be taught how to use the new parsing Json API (JSR-353) in JAVA EE 7 in container GlassFish 4 of JAVA EE 7, as well as a combination of jQuery and Bootstrap. This article requires the reader to have some basic knowledge of HTML 5 Websocket.

Effect picture

Let's first take a look at the effect after completing this tutorial, as shown below:

Preparatory work

We are using the construction of JDK 7 and MAVN 3 libraries. Let's first look at the section on Jave EE 7 in pom.xml:

${project.build.directory} / endorsed UTF-8 javax javaee-api 7.0 provided org.apache.maven.plugins maven-compiler-plugin 3.1 1.7 ${endorsed.dir} org.apache.maven.plugins maven-war-plugin 2.3 false org.apache.maven.plugins Maven-dependency-plugin 2.6 [..]

At the same time, in order to use GlassFish 4, you need to add the following plug-ins:

Plugin > org.glassfish.embedded maven-embedded-glassfish-plugin 4.0 embedded-glassfish ${basedir} / target/$ {project.artifactId}-${project.version} .war true 8080 ${project.artifactId} hascode deploy

Set the Endpoint of Websocket

Let's first take a look at the server Websocket code as follows, and then do further parsing:

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 Session session, @ 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 (Sessions: session.getOpenSessions ()) {if (s.isOpen () & & room.equals (s.getUserProperties (). Get ("room") {s.getBasicRemote () .sendObject (chatMessage) } catch (IOException | EncodeException e) {log.log (Level.WARNING, "onMessage failed", e);}

Face analysis of the above code:

Use @ ServerEndpoint to define a new endpoint where the value specifies URL and the PathParams parameter can be used, just as it is used in JAX-RS.

So the value "/ chat/ {room}" allows the user to connect to a chat room through the following form of URL: ws://0.0.0.0:8080/hascode/chat/java

The values in curly braces (that is, room) can be injected as parameters in the endpoint's lifecycle callback method by using javax.websocket.server.PathParam.

In addition, we will use an encoded and decoded class because we are using a class in the form of DTO that is used to transfer data between the server and the client.

When the user connects to the server for the first time and enters the room number to enter the chat room, the room number is injected and submitted as a parameter, and the value is stored in the user's attribute map using session.getUserProperties.

When a chat participant sends information to the server over a tcp connection, it loops through all open session, each session is bound to a designated chat room, and receives encoded and decoded information.

If we want to send simple text messages or messages in binary format, we can use session.getBasicRemote (). SendBinary () or session.getBasicRemote (). SendText ()

Next, let's take a look at the code that represents the messaging 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 will be written to convert between chat messages and JSON formats.

Let's first take a look at the implementation of the decoding class, which converts the chat message passed to the server into a ChatMessage entity class. In this case, Java API for JSON Processing (JSR353) is used (see:

Http://jcp.org/en/jsr/detail?id=353) specification to convert the information in JSON format into an entity class, 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 {@ Override public void init (final EndpointConfig config) {} @ Override public void destroy () {} @ Override public ChatMessage decode (final String textMessage) 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, take a look at the code for the coding class, which, by contrast, converts the ChatMessage class to Json format, 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 {@ 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 () }}

You can see the power of JSR-353 here, and you can easily convert a DTO object to JSON by calling Json.createObjectBuilder.

Build a simple client through Bootstrap and Javacsript

Finally, we use the famous Bootstrap, jQuery framework and Javascript to design a simple client. We create a new index.html file in the src/main/weapp directory with the following code:

[..] Var wsocket; var serviceLocation = "ws://0.0.0.0:8080/hascode/chat/"; var $nickName; var $message; var $chatWindow; var room =''; function onMessageReceived (evt) {/ / var msg = eval ('('+ evt.data +')'); var msg = JSON.parse (evt.data) / / native API var $messageLine = $(''+ msg.received +''+ msg.sender +''+ msg.message +'); $chatWindow.append ($messageLine) } function sendMessage () {var msg ='{"message": "'+ $message.val () +'", "sender": "'+ $nickName.val () +'", "received": ""}'; wsocket.send (msg); $message.val (''). Focus () } function connectToChatserver () {room = $('# chatroom option:selected'). Val (); wsocket = new WebSocket (serviceLocation + room); wsocket.onmessage = onMessageReceived;} function leaveRoom () {wsocket.close (); $chatWindow.empty (); $('.chat-wrapper') .hide (); $(' .chat-signin') .show () $nickName.focus ();} $(document) .ready (function () {$nickName = $('# nickname'); $message = $('# message'); $chatWindow = $('# response'); $('. Chat-wrapper'). Hide (); $nickName.focus (); $('# enterRoom') .click (function (evt) {evt.preventDefault ()) ConnectToChatserver (); $('.chat-wrapper h3'). Text (' Chat #'+ $nickName.val () + "@" + room); $('.chat-signin') .hide (); $(' .chat-wrapper') .show (); $message.focus ();}) $('# do-chat') .submit (function (evt) {evt.preventDefault (); sendMessage ()}); $('# leave-room') .click (function () {leaveRoom ();});}) Chat sign in Nickname Chatroom arduino java groovy scala Sign in Enter your message.. Leave room

In the above code, note the following:

To call websocket on the Javascript side, you can initiate the connection as follows: 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 var wsocket = new WebSocket ('ws://0.0.0.0:8080/hascode/chat/java')

To get the information returned from the server, you only need to set the corresponding method to get the returned information in the callback function wsocket.onmessage.

To send a Websocket message to the server, the method is wsocket.send (), where messages that can be sent can be text or binary data.

Wsocket.close () is used to close the connection.

There are many other uses in Websocket. For more information, please refer to its standard specification document (http://tools.ietf.org/html/rfc6455).

In the end, we passed

Mvn package embedded-glassfish:run

Deploy the code, and then you can see the effect of some screenshots at the beginning of this article.

After reading the above, do you have any further understanding of how to use JavaEE7, Websockets and GlassFish4 to create chat rooms (1)? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report