Use Java and WebSocket to implement a web chat room instance code _java

Source: Internet
Author: User
Tags http request sessions time interval tomcat tomcat server

Before we introduce the main body, let me introduce the background and principle of websocket:

Background

In the browser can only achieve one-way communication through HTTP, comet can simulate two-way communication to some extent, but the efficiency is low, and need the server to have better support; The sockets and Xmlsocket in Flash enable true two-way communication, and you can use these two features in JavaScript with Flex Ajax Bridge. It can be foreseen that if WebSocket is implemented in the browser, it will replace the above two technologies and be widely used. In the face of this situation, HTML5 defines the WebSocket protocol, which can better save the server resources and bandwidth and achieve real-time communication.

The WebSocket protocol is also implemented in the JavaEE7.

Principle

WebSocket protocol.

Many web sites in order to achieve instant messaging, the technology used is polling (polling). Polling is a browser that sends HTTP request to the server at a specific time interval, such as every 1 seconds, and then returns the latest data to the client by the server. The traditional HTTP request pattern has obvious drawbacks-browsers need to constantly make requests to the server, but the header of HTTP request is very long, and the useful data contained in it may be just a small value, which takes up a lot of bandwidth.

And the new technology to do polling effect is comet– with Ajax. However, although this technology can achieve full-duplex communication, but still need to issue a request.

In the WebSocket API, the browser and the server only need to do a handshake action, and then, between the browser and the server to form a fast path. The data can be transmitted directly between the two. In this WebSocket agreement, there are two great benefits to implementing instant Service:

1. Header

The header that communicates with each other is very small-about 2 Bytes.

2. Server Push

Server push, the server no longer passively received the browser request before returning data, but in the new data when the initiative to push to the browser.

I. Introduction of the Project

WebSocket is HTML5 a new protocol, it implements the browser and server Full-duplex communication, here will use the WebSocket to develop the web chat room, the front-end framework will use the AMAZEUI, the backstage uses the Java, the editor uses the Umeditor.

Ii. knowledge-related points

Web front-end (HTML+CSS+JS) and Java

Third, Software Environment Tomcat 7 JDK 7 Eclipse Java EE modern browser

Four, the effect screenshot

Effect 1

Effect 2

V. Project Combat

1. New Project

Open Eclipse Java EE, create a new dynamic Web Project named Chat, and then import the packages needed to process the JSON format string, Commons-beanutils-1.8.0.jar, Commons-collections-3.2.1.jar, Commons-lang-2.5.jar, Commons-logging-1.1.1.jar, The Ezmorph-1.0.6.jar and Json-lib-2.4-jdk15.jar packages are placed in the Webcontent/web-inf/lib directory, and the project is finally posted to the Tomcat server, and the empty project is completed.

2. Writing front page

Create a new page in the WebContent directory called Index.jsp, which uses the AMAZEUI framework, which is a cross-platform, adaptive front-end framework that uses Umeditor, a rich text online editor that makes our message content colourful.

First download the package from the Amazeui official website, and then unzip the assets folder to the WebContent directory, so we can use Amazeui.

Again from Uediter official website Download mini version of the JSP version of the compression package, after decompression the entire directory copy to the WebContent directory, then you can write the front-end code, the code is as follows (you can write according to your own preferences):

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%> <! DOCTYPE html>  

When you finish writing, start the Tomcat server and then access http://localhost:8080/Chat/index.jsp, and you'll see the following interface.

3. Writing Background code

Create a new Com.shiyanlou.chat package that creates a class named Chatserver in the package, unifying the WebSocket API from Java EE 7, so whatever the server, the Java code is the same, the code is as follows:

Package com.shiyanlou.chat;
Import Java.text.SimpleDateFormat;
Import Java.util.Date;
Import Javax.websocket.OnClose;
Import Javax.websocket.OnError;
Import Javax.websocket.OnMessage;
Import Javax.websocket.OnOpen;
Import javax.websocket.Session;
Import Javax.websocket.server.ServerEndpoint;
Import Net.sf.json.JSONObject; /** * Chat Server class * @author Shiyanlou * */@ServerEndpoint ("/websocket") public class Chatserver {private static final Si	Mpledateformat date_format = new SimpleDateFormat ("Yyyy-mm-dd hh:mm");  Date format @OnOpen public void Open (session session) {//Add initialization action}/** * Accept client messages and send messages to all connected sessions * @param message Message sent by client * * @param session client's sessions/@OnMessage public void GetMessage (String message, conversation) {//the client's
  Message resolution to JSON object Jsonobject Jsonobject = jsonobject.fromobject (Messages);
  Adds a send date to the message Jsonobject.put ("date", Date_format.format (new Date ()); Send the message to all connected sessions for (session openSession:session.getOpenSessions ()) {//Add whether this message is currentThe session itself is marked Jsonobject.put ("Isself", opensession.equals);
  Sends the JSON-formatted message opensession.getasyncremote (). SendText (Jsonobject.tostring ()); @OnClose public void Close () {//Add action at shutdown session} @OnError public void error (Throwable t) {//Add action to handle error}}

4. Front and rear interaction

Backstage, the front to use WebSocket connection background, need to create a new WebSocket object, and then you can interact with the server side, from the browser to send messages to the server side, and to verify the contents of the input box is empty, and then accept the message sent by the service side, Add them dynamically to the chat content box in the

var um = um.geteditor (' Myeditor ');
$ (' #nickname ') [0].focus (); New WebSocket object, final/websocket corresponding server-side @serverendpoint ("/websocket") var socket = new WebSocket (' ws://${ PageContext.request.getServerName ()}:${pagecontext.request.getserverport ()}${pagecontext.request.contextpath}/
   WebSocket ');
   Processing server-side sent data Socket.onmessage = function (event) {addmessage (event.data);
   };
    Click the Send button when the action $ (' #send '). On (' click ', function () {var nickname = $ (' #nickname '). Val ();
     if (!um.hascontents ()) {//Determine if the message input box is a null//message input box get focus um.focus ();
     Add Jitter Effect $ ('. Edui-container '). addclass (' Am-animation-shake ');
    SetTimeout ("$ ('. Edui-container '). Removeclass (' Am-animation-shake ')", 1000);
     else if (nickname = =) {//Judge whether the nickname box is empty//nickname Box get focus $ (' #nickname ') [0].focus ();
     Add Jitter Effect $ (' #message-input-nickname '). addclass (' Am-animation-shake ');
    SetTimeout ("$ (' #message-input-nickname '). Removeclass (' Am-animation-shake ')", 1000); else {//Send Message
     Socket.send (Json.stringify ({content:um.getContent (), nickname:nickname}));
     Empty the Message input box Um.setcontent (");
    The message input box gets the focus Um.focus ();
   }
   });
    Add the message to the chat content function addmessage (messages) {json.parse); var messageitem = ' <li class= ' am-comment ' + (message.isself? ' Am-comment-flip ': ' am-comment ') + ' > ' + ' <a href= ' javascript:void (0) "></a> ' + ' ;d IV class= "Am-comment-main" > 

At this point, the simple web chat room is complete, you can open a few more Windows or on the LAN to invite small partners to test together.

Vi. Summary

The project class uses WebSocket to realize a simple web chat room, in fact, websocket not only can be applied to the browser, but also can be applied to desktop clients.

Seven, study questions

This project class is simply the realization of the chat room, in fact, there are many functions can be increased, such as Avatar upload function, one-on-one chat function, let us together to improve the chat room bar.

See here do not want to try right away, click here---to provide you with free online compilation environment, so that you no longer to build the environment and worry

The above is a small set to introduce the use of Java and websocket to achieve a web chat room instance code related knowledge, hope to help everyone, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Related Article

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.