Use Java WebSocket to make a chat room _java

Source: Internet
Author: User
Tags sessions

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.

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.