Realization of online conference room system with AJAX+J2EE

Source: Internet
Author: User
Tags add end final functions socket string stub thread
Everyone is speculating on Web 2.0 this year, and one of the technologies, Ajax, is also on fire. Therefore, I wrote an article called "Flick AJAX" earlier, and briefly analyzed the essence of Ajax technology. Although I don't like to follow suit, there are some places where Ajax is more useful. Some time ago I made the online conference system of the EasyJF open source team and used Ajax technology. Let me share the design ideas with you.

First, the functions implemented by the system

This conference room system is mainly used by members of the EasyJF open source team for online conferences. The conference system simulates traditional conferences and can open multiple conference rooms with different topics at the same time. Each conference room needs to provide access control functions. It can be specified during the conference. Conference speaking mode (divided into queue speaking and free speaking), the system can automatically record the speaking information of each conference room, which can be consulted by the participants for a long time.

The user of the conference system supports the visitor account to participate in the conference, and also provides an interface with other user systems, such as the open source forum system on the EasyJF official website.

The conference system temporarily uses the text chat mode and provides voice and video interfaces.

II.Technical System

The server uses Java language, MVC uses EasyJWeb framework;
The client uses AJAX technology to interact with the server;
The format of the conference history information is in text format, which is convenient for system installation and management.

Third, the server-side design of the conference room.

 The server side of the conference room is the core part of the entire conference system. The quality of the server-side program design affects the quality of the entire system.

First, perform an abstract analysis based on the functions to be implemented in the conference room. A conference room object should include parameters such as conference theme, conference profile, number of participants, announcements, conference room type, access rights settings, room password, current participants, currently speaking speakers, and people waiting in line to speak. information. We encapsulate him in a Java object. As shown in the following ChatRoom code:

public class ChatRoom {
private String cid; // Primary key
private String title; // chat theme
private String intro; // Chat room introduction
private String announce; // chat room announcement
private String owner; // Chat creator
private Integer maxUser; // Maximum number of online users
private Integer intervals; // Maximum refresh interval
private String vrtype; // Access
private String vrvalue; // Access value
private Integer status; // Chat room status
private Date inputTime;
}
Need a class to manage the conference room, and all operations related to the conference (such as starting a conference, closing a conference), etc. should be directed to him. This class should also have functions such as automatic timing detection of the user's online status (to prevent the user from accidentally exiting), and saving the conference history speech information in the memory to a text file. Here you can consider using a ChatService class to provide these functions:


public class ChatService implements Runnable {
private static final Map service = new HashMap (); // Conference room service, the current conference room in the system is stored in the table collection
private static final int maxServices = 10; // The maximum number of meeting rooms that can be opened at the same time
private static final SimpleDateFormat df = new SimpleDateFormat ("yyyy-MM-dd");
private final List msgs; // chat information Chat
private final List users; // Online users, ChatUser
private final List talkers; // Number of queued speakers Talker
private final List manager; // Meeting room manager
private Talker currentTalker; // Current speaker
public ChatService ()
{
this.msgs = new ArrayList ();
this.users = new ArrayList ();
this.talkers = new ArrayList ();
this.manager = new ArrayList ();
this.maxUser = 1000; // Maximum 1000 people at the same time
this.interval = 1000 * 60 * 5; // 5 minutes ago
}
}
Conference speech information also needs to be encapsulated into a class, which indicates the speaker, recipient, content, speaking time, type, etc., which is roughly the following Chat class:

public class Chat {
private String cid;
private String sender;
private String reciver;
private String content;
private Date vdate;.
private Integer types;
private Integer status;
}
There is also information indicating the people who participated in the meeting, including the participant's name, IP address, status, etc., as shown in the following ChatUser class:

public class ChatUser {
private String ip;
private String port;
private String userName;
private Date lastAccessTime;
private Integer status;
}


Another Talker class is needed to indicate the current speaker, indicating the current speaker, the start time of the speech, the estimated end time of the speech, etc.

In the server-side design, the conference room information server should be able to run in a multi-threaded manner, that is, a new thread is started when a conference is started, and each conference thread maintains its own conference status, such as participants, speakers, and saves the conference history Operations such as speaking information and clearing data in memory.

Fourth, client design

The conference room client includes two parts, one is the management interface of the conference room, which mainly includes the operation of "add, delete, change, check" and "start" or "close" the conference room. In this part, we can directly use AbstractCrudAction, the business engine for adding, deleting, modifying, and checking in EasyJWeb Tools, which can be quickly implemented. The interface is also relatively simple and can be generated directly using the EasyJWeb Tools code generation tool engine. The client for conference room management is traditional Java Web technology, so there is nothing to consider.

The second part of the client is the main part of the conference system. This part has two interfaces. The first page is the selection page for the conference room. That is, the conference rooms that have been started are listed. The user selects a conference room to enter. This page also uses traditional Java Web technology. The second page is the main interface after entering the conference room. This interface is the main interface of the entire conference system. All operations involved in the conference are run here. This interface needs to continuously interact with the server to transmit data. The content of the transmission includes the user's speech, other people's speech to the user, and the status of the conference room. Some transmission information needs immediate response (such as user speaking), and some information can be set to respond regularly (such as conference room status).


There are two main ways to interact with the server in the Java Web program. One is to directly refresh the page, and the other is to directly communicate with the Web server port using Socket. Because Socket programming is relatively complicated, we choose the first method to directly refresh the page. This method can be divided into several types, including traditional Form submission, traditional automatic refreshing of the web page to obtain data, and the use of ActiveXObject objects (such as xmlhttp) directly with The server interacts with the data, which is AJAX. Because the user does not feel the page is refreshing using the AJAX method, it performs better than the manual or automatic refresh method, so we decided to choose the AJAX method to implement data interaction between the client and the server.

When the user speaks, use the xmlhttp object to post the data directly to the server. In order to continuously receive other people's speech information, it is necessary to periodically read data from the server. Therefore, you need to start a timer on the client side, and automatically use the xmlhttp object to download the other person's speech information at regular intervals. It will be displayed in the main interface of the conference room information. In addition, the conference status information such as the number of participants, current speakers in the conference room, and announcements in the conference room must be refreshed regularly. This can also be obtained by starting a timer from the client and interacting with the server through the xmlhttp object.

 

     In addition, there are some operations, such as locking the meeting room, kicking people, designating the speaking time of the speaker, adding passwords to the meeting room, etc., and also implementing commands with the server through xmlhttp. ...

 

Five, core code description

1, server-side core code

In the conference system of the EasyJF open source team, the forum system and background management of the EasyJF official website are integrated together. The server ChatService and ChatRoom are merged into a ChatService.java class to implement conference room management and conference service functions. The main code of the ChatService class is as follows:

package com.easyjf.chat.business;
public class ChatService implements Runnable {
Private static final Map service = new HashMap (); // Meeting room service, the current meeting room in the system is stored in the table collection
Private static final int maxServices = 10; // The maximum number of conference rooms that can be opened at the same time
Private static final SimpleDateFormat df = new SimpleDateFormat ("yyyy-MM-dd");
Private final List msgs; // chat information Chat
Private final List users; // Online users, ChatUser
Private final List talkers; // Number of queued speakers Talker
Private final List manager; // Meeting room manager
Private Talker currentTalker; // Current speaker
Private String cid; // meeting room id
Private String title; // Meeting room theme
Private String intro; // Meeting room introduction
Private String owner; // Conference room creator.
Private int maxUser; // Maximum number of users online
Private int interval; // Maximum refresh interval
Private String vrtype; // access
Private String vrvalue; // access value
Private String announce;
Private String password; // room access password
Private int status; // Meeting room status
Private String filePath;
// private Thread thread;
Private boolean isStop = false;
Public ChatService ()
{
This.msgs = new ArrayList ();
This.users = new ArrayList ();
This.talkers = new ArrayList ();
This.manager = new ArrayList ();
This.maxUser = 1000; // Maximum 1000 people at the same time
This.interval = 1000 * 60 * 5; // 5 minutes ago
}
/ **
* Stop all meeting rooms
*
* /
Public static void clear ()
{
If (! Service.isEmpty ())
{
Iterator it = service.values (). Iterator ();
While (it.hasNext ())
{
ChatService chat = (ChatService) it.next ();
Chat.stop ();
}
}
Service.clear ();
}
/ **
* Create a meeting room
* @Param name Conference Room ID
.
* @Return
* /
Public static ChatService create (String name)
{
ChatService ret = null;
If (service.containsKey (name))
{
ChatService s = (ChatService) service.get (name);
S.stop ();
Service.remove (name);
}
If (service.size () <maxServices)
{
Ret = new ChatService ();
Service.put (name, ret);
}
Return ret;
}
/ **
* Stop a conference room
* @Param name Conference Room ID
* @Return
* /
Public static boolean close (String name)
{
ChatService chatRoom = ChatService.get (name);
If (chatRoom! = Null)
{
ChatRoom.stop ();
Service.remove (name);
}
Return true;
}
/ **
* Get a meeting room information
* @Param name Conference Room ID
* @Return
* /
Public static ChatService get (String name)
{
If (service.containsKey (name)) return (ChatService) service.get (name);.
Else return null;
}
Public void run () {
// TODO Auto-generated method stub
//This.thread=Thread.currentThread ();
While (! IsStop)
{
//System.out.println("Start monitoring a conference room! "This.title);
This.flash ();
Try {
Thread.sleep (5000);
}
Catch (Exception e)
{
E.printStackTrace ();
}
}
//System.out.println("End! ");
}
Public void stop ()
{
This.flashAll ();
IsStop = true;
}
// Someone is speaking in the conference room
Public boolean talk (Chat chat)
{
Boolean ret = false;
If (canTalk (chat.getSender ()))
{
This.msgs.add (chat);
Ret = true;
}
Return ret;
}
Public boolean exit (ChatUser user)
{
Talk (geneSystemMsg (user.getUserName () "Quit the conference room!"));
Return this.users.remove (user);
}
}
// Refresh information and save meeting information
public void flash ()
{
FlashChatMsg ();
FlashChatUser ();
}.
}
2 、 Action code of MVC processing part

In EasyJF's conference system, because EasyJWeb is used as the MVC framework, it is relatively simple to handle Ajax. The following is the main Action code of the conference room system.

package com.easyjf.chat.action;
public class ChatAction extends AbstractCmdAction {
Private ChatService chatRoom;
Public Object doBefore (WebForm form, Module module) {
// TODO Auto-generated method stub
If (chatRoom == null) chatRoom = ChatService.get ((String) form.get ("cid"));
Return super.doBefore (form, module);
}
Public Page doInit (WebForm form, Module module) {
// TODO Auto-generated method stub
Return doMain (form, module);
}
// User logs in to the conference room
Public Page doMain (WebForm form, Module module) {
If (chatRoom! = Null) {
ChatUser user = getChatUser ();
If (! ChatRoom.join (user)) form.addResult ("msg", "Cannot join the room, maybe the permissions are insufficient!");

 form.addResult ("chatRoom", chatRoom);
Form.addResult ("user", user);
}
Else
{
Form.addResult ("msg", "The conference has not started or the conference room does not exist!");
}
Return module.findPage ("main");
}
// Process the user's speech
Public Page doSend (WebForm form, Module module) {
If (chatRoom == null) return new Page ("err", "/ err.html", "thml"); // The error that the conference room does not exist
Chat chat = (Chat) form.toPo (Chat.class);
Chat.setCid (chatRoom.geneId ());
ChatRoom.talk (chat);
Return doRecive (form, module);
}
// Users receive speech information
Public Page doRecive (WebForm form, Module module) {
If (chatRoom == null) return new Page ("err", "/ err.html", "thml"); // The error that the conference room does not exist
String lastReadId = CommUtil.null2String (form.get ("lastReadId"));
//System.out.println(lastReadId);
Form.addResult ("list", chatRoom.getNewestMsg (getChatUser (), lastReadId));
Return module.findPage ("msgList");
}
// The user refreshes the conference status information
Public Page doLoadConfig (WebForm form, Module module) {.
If (chatRoom == null) return new Page ("err", "/ err.html", "thml"); // The error that the conference room does not exist
Form.addResult ("userList", chatRoom.getUsers ());
Form.addResult ("talkerList", chatRoom.getTalkers ());
Return module.findPage ("config");
}
// User exit
Public Page doExit (WebForm form, Module module) {
If (chatRoom == null) return new Page ("err", "/ err.html", "thml"); // The error that the conference room does not exist
HatRoom.exit (getChatUser ());
Form.addResult ("msg", "Exit successfully");
ActionContext.getContext (). GetSession (). RemoveAttribute ("chatUser");
Return new Page ("msg", "/ chat / xmlMsg.xml", Globals.PAGE_TEMPLATE_TYPE);
}
3.AJAX client core code

In EasyJF conference system, the server sends to the client all formatted xml document data. The following is the core AJAX function and client code for sending and receiving meeting information.

function newXMLHttpRequest () {
Var xmlreq = false;
If (window.XMLHttpRequest) {
Xmlreq = new XMLHttpRequest ();
} Else if (window.ActiveXObject) {.
Try {
Xmlreq = new ActiveXObject ("Msxml2.XMLHTTP");
} Catch (e1) {
Try {
Xmlreq = new ActiveXObject ("Microsoft.XMLHTTP");
} Catch (e2) {
}
}
}
return xmlreq;
}
// Process the returned information
// xmlHttp return value,
// method: method name method must take a parameter such as doRecive (xNode);
function handleAjaxResult (req, method) {
Return function () {
If (req.readyState == 4) {
If (req.status == 200) {
// Pass the XML containing the response information to the processing function
Var objXMLDoc = new ActiveXObject ("Microsoft.XMLDOM");
ObjXMLDoc.loadXML (req.responseText);
Eval ("if (objXMLDoc.firstChild)" method "(objXMLDoc.firstChild.nextSibling);");
} Else {
// alert ("HTTP error:" req.status);
}
}
}
}
// Execute the client Ajax command
// url data post address
// postData packet
// handleMethod Handling the returned method
Function executeAjaxCommand (url, postData, handleMethod) ...
{
Var req = newXMLHttpRequest ();
Req.onreadystatechange = handleAjaxResult (req, handleMethod);
Req.open ("PO ST", url, true);
Req.setRequestHeader ("Content-Type", "application / x-www-form-urlencoded");
Req.setRequestHeader ("charset", "utf-8");
Req.send (postData);
}
// The user speaks
unction doSend ()
{
If (! Check ()) return false;
Var msg = EditForm.content.value;
Var reciver = EditForm.reciver.value;
Var url = "/ chat.ejf? EasyJWebCommand = send & cid =" roomId "& lastReadId =" lastReadId;
Var postData = "sender =" myName "& reciver =" reciver "& content =" msg;
ClearTimeout (reciveTime);
ExecuteAjaxCommand (url, postData, "recive");
EditForm.content.value = "";
}
// Receive information
function doRecive ()
{
Var reciver = EditForm.reciver.value;
Var url = "/ chat.ejf? EasyJWebCommand = recive & cid =" roomId "& lastReadId =" lastReadId;
ExecuteAjaxCommand (url, "", "recive");
}
// Process the received speech information
function recive (list).
{
Var id = "";
For (var oNode = list.firstChild; oNode; oNode = oNode.nextSibling) // analyze each node in turn
{
ChatContent.innerHTML = showMsg (oNode);
Id = oNode.getAttribute ("cid");
}
If (id! = "") LastReadId = id;
ChatContent.scrollTop = chatContent.scrollHeight;
ReciveTime = setTimeout ("doRecive ();", 5000);
}
六 、 System Demo

Everyone can go to the official website of the EasyJF open source team to see the program demonstration effect, the address is:

Http://www.easyjf.com/chatRoom.ejf?easyJWebCommand=show&ejid=2538093638804337

Concluding remarks

Ajax is technically mainly javascript, dhtml, css, xmldom, xmlhttp and other technologies we have been in contact with for a long time. And xmldom and xmlhttp have nothing. When you write the program, open the reference document and copy it. OK, dhtml and javascript have more things. You ca n’t just look at the reference document. You need to really digest it and be able to use it flexibly. Need everyone to practice. The author advises everyone not to abuse Ajax. For experts, it is recommended to study more business and system-level algorithm design. For novices, the basic technology (client includes dhtml, css, javascript, xml, etc.), J2EE server-side design patterns, UML modeling, Servlet, JDBC or ORM System, XML, EJB, and some frameworks, tools, etc.) Learn well is the last word.


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.