Before introducing the main text, let me introduce the background and principles of websocket to you:
background
Only one-way communication can be achieved through http in the browser. Comet can simulate two-way communication to a certain extent, but it is low in efficiency and requires good support from the server; socket and xmlsocket in flash can realize true two-way communication, and these two functions can be used in JavaScript through flex ajax bridge. It can be foreseeable that if websocket is implemented in the browser, it will replace the above two technologies and be widely used. Faced with this situation, HTML5 defines the WebSocket protocol, which can better save server resources and bandwidth and achieve real-time communication.
The WebSocket protocol is also implemented in JavaEE7.
principle
WebSocket protocol .
Nowadays, in order to realize instant communication, many websites use polling. Polling is to send an HTTP request to the server at a specific time interval (such as every 1 second), and the server returns the latest data to the client's browser. This traditional HTTP request pattern brings obvious disadvantages. The browser needs to continuously make requests to the server. However, the header of the HTTP request is very long, and the useful data contained in it may be just a small value, which will occupy a lot of bandwidth.
The effect of a newer technology to do polling is that Comet uses AJAX. However, although this technology can achieve full-duplex communication, it still requires a request.
In the WebSocket API, the browser and the server only need to shake hands, and then a fast channel is formed between the browser and the server. Data can be transmitted directly between the two. In this WebSocket protocol, we have two major benefits to implementing instant service:
1. Header
The header that communicates with each other is very small - probably only 2 Bytes
2. Server Push
When pushing by the server, the server no longer passively receives the browser's request before returning data, but actively pushes it to the browser when new data is available.
1. Project Introduction
WebSocket is a new protocol in HTML5. It implements full duplex communication between the browser and the server. Here, WebSocket will be used to develop web chat rooms. The front-end framework will use AmazeUI, Java in the background, and UMEditor in the editor.
2. Involving knowledge points
Web front-end (HTML+CSS+JS) and Java
3. Software environment Tomcat 7 JDK 7 Eclipse JavaEE Modern browser
4. Effect screenshot
Effect 1
Effect 2
5. Project practical combat
1. Create a new project
Open Eclipse JavaEE, create a new Dynamic Web Project named Chat, and then import the packages required to process JSON format strings, place commons-beanutils-1.8.0.jar, commons-collections-3.2.1.jar, commons-lang-2.5.jar, commons-logging-1.1.jar, ezmorph-1.0.6.jar and json-lib-2.4-jdk15.jar and other packages are placed in the WebContent/WEB-INF/lib directory, and finally publish the project to the Tomcat server. At this point, the empty project is completed.
2. Write front-end page
Create a new page named index.jsp in the WebContent directory. The AmazeUI framework is used here. It is a cross-screen adaptive front-end framework. The message input box uses UMEditor, which is a rich text online editor that can make our message content colorful.
First, download the compressed package from the AmazeUI official website, and then unzip the assets folder and copy the WebContent directory, so that we can use AmazeUI.
Then download the Mini version of JSP version compression package from the UEditer official website, unzip the entire directory into the WebContent directory, and then you can write the front-end code, the code is as follows (you can write it according to your preference):
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE html><html lang="zh"><head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"><title>ShiYanLou Chat</title><!-- Set render engine for 360 browser --><meta name="renderer" content="webkit"><!-- No Baidu Siteapp--><meta http-equiv="Cache-Control" content="no-siteapp" /><link rel="alternate icon" href="assets/i/favicon.ico"><link rel="stylesheet" href="assets/css/amazeui.min.css"><link rel="stylesheet" href="assets/css/app.css"><!-- umeditor css --><link href="umeditor/themes/default/css/umeditor.css" rel="stylesheet"><style>.title { text-align: center;}.chat-content-container { height: 29rem; overflow-y: scroll; border: 1px solid silver;}</style></head><body> <!-- title start --> <div> <div> <div> <div> <h1>ShiYanLou Chat</h1> </div> </div> </div> </div> <!-- title end --> <div> <div> <ul id="message-list"></ul> </div> </div> </div> </div> <!-- chat content start --> <!-- message input start --> <div> <div> <form> <div> <script type="text/plain" id="myEditor"></script> </div> </form> </div> </div> <div> <div> <div> <div> <div> <div id="message-input-nickname"> <span><i></i></span> <input id="nickname" type="text" placeholder="Please enter nickname"/> </div> </div> <div> <script src="assets/js/jquery.min.js"></script> <!--<!--[if lte IE 8 ]> <script src="http://libs.baidu.com/jquery/1.11.1/jquery.min.js"></script> <!--<!--<!--[if lte IE 8 ]> <script src="http://libs.baidu.com/jquery/1.11.1/jquery.min.js"></script> <!--> <!-- umeditor js --> <script charset="utf-8" src="umeditor/umeditor.config.js"></script> <script charset="utf-8" src="umeditor/umeditor.min.js"></script> <script src="umeditor/lang/zh-cn/zh-cn.js"></script> <script> $(function() { // Initialize the message input box var um = UM.getEditor('myEditor'); // Make the nickname box get focus $('#nickname')[0].focus(); }); </script></body></html>After writing, start the Tomcat server, and then visit http://localhost:8080/Chat/index.jsp and you will see the following interface.
3. Write background code
Create a new package of com.shiyanlou.chat, create a class called ChatServer in the package. The WebSocket API has been unified since JavaEE 7. Therefore, no matter what server it is, the code written in Java is the same, and 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 SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm");// Date formatting @OnOpen public void open(Session session) { // Add initialization operation} /** * Accept the client's message and send the message to all connected sessions* @param message Message from the client* @param session The client's session*/ @OnMessage public void getMessage(String message, Session session) { // parse the client's message into a JSON object JSONObject jsonObject = JSONObject.fromObject(message); // Add the send date in the message jsonObject.put("date", DATE_FORMAT.format(new Date())); // Send the message to all connected sessions for (Session openSession : session.getOpenSessions()) { // Add the flags of whether this message is the current session itself jsonObject.put("isSelf", openSession.equals(session)); // Send a JSON-formatted message openSession.getAsyncRemote().sendText(jsonObject.toString()); } } @OnClose public void close() { // Add an operation when closing the session} @OnError public void error(Throwable t) { // Add an operation to handle error}}4. Front and backstage interaction
After writing the background, the front desk needs to use WebSocket to connect to the background. You need to create a new WebSocket object, and then you can interact with the server, send messages from the browser to the server, and at the same time verify whether the content of the input box is empty, then accept messages sent by the server, dynamically add them to the chat content box,
var um = UM.getEditor('myEditor');$('#nickname')[0].focus();// Create a new WebSocket object, and the last /websocket corresponds to the server-side @ServerEndpoint("/websocket")var socket = new WebSocket('ws://${pageContext.request.getServerName()}:${pageContext.request.getServerPort()}${pageContext.request.contextPath}/websocket'); // Process data sent by the server-side socket.onmessage = function(event) { addMessage(event.data); }; // Action $('#send').on('click', function() { var nickname = $('#nickname').val(); if (!um.hasContents()) {// Determine whether the message input box is empty // The message input box gets focus um.focus(); // Add jitter effect $('.edui-container').addClass('am-animation-shake'); setTimeout("$('.edui-container').removeClass('am-animation-shake')", 1000); } else if (nickname == '') {// Determine whether the nickname box is empty //Nickname box gets 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 })); // Clear message input box um.setContent(''); // Message input box gets focus um.focus(); } }); // Add message to chat content function addMessage(message) { message = JSON.parse(message); var messageItem = '<li>' + '<a href="javascript:void(0)" ><img src="assets/images/' + (message.isSelf ? 'self.png' : 'others.jpg') + '"//</a>' + '<div><header><div>' + '<a href="javascript:void(0)">' + message.nickname + '</a> <time>' + message.date + '</time></div></header>' + '<div>' + message.content + '</div></div></li>'; $(messageItem).appendTo('#message-list'); // Scroll the scrollbar to the bottom $(".chat-content-container").scrollTop($(".chat-content-container")[0].scrollHeight); }At this point, a simple web chat room is completed. You can open several more windows or invite friends to test together on the LAN.
6. Summary
This project class uses WebSocket to implement a simple web chat room. In fact, WebSocket can not only be applied to the browser, but also to desktop clients.
7. Thinking questions
This project class is just a simple implementation of the chat room. In fact, there are many functions that can be added, such as the avatar upload function, one-to-one chat function, etc. Let’s improve the chat room together.
Do you want to try it right away if you see this? Click here--- Provide you with free online compilation environment so that you no longer have to worry about building an environment
The above is the relevant knowledge about using Java and WebSocket to implement web chat room example code introduced to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!