In a recent project, you need to use the Java websocket new features, so I learned that the technology is quite fun, and instantly know the Web page above the online customer service is how to do it.
First look at the picture:
Multi-client is implemented for real-time communication.
Look at the Code Project structure Chart: Very simple, 1 classes, 1 pages
Then look at the specific code
Look at the back-end code First
Package com.main;
Import java.io.IOException;
Import Java.util.concurrent.CopyOnWriteArraySet;
Import javax.websocket.*;
Import Javax.websocket.server.ServerEndpoint; /** * @ServerEndpoint Annotation is a class-level annotation, its function is mainly to define the current class as a websocket server, * The value of the annotation will be used to listen to the user connected terminal access URL address, the client can connect to the Web through this URL The socket server Side/@ServerEndpoint ("/websocket") public class H5servletserversocket {//static variable, used to record the current number of online connections.
It should be designed to be thread-safe.
private static int onlinecount = 0; The thread-safe set of the concurrent package, which holds the corresponding Mywebsocket object for each client. To enable the server to communicate with a single client, you can use a map to store it, where key can identify the user with the private static copyonwritearrayset
Next is the front-end page code:
<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <% String Path = Request.getcontextpath ()
;
String basepath = request.getscheme () + "://" + request.getservername () + ":" + request.getserverport () + path + "/"; %> <! DOCTYPE html>
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.