Use tomcat to implement comet chat rooms based on IFRAME streaming

Source: Internet
Author: User
Tags html comment sendmsg

First, no picture, no truth, first:

This is a chat room demo Based On Comet. Its function is similar to QQ chat. If there is a new message in the chat process, the server needs to push the message to the browser, So comet technology can be used here.

Comet generally has two implementation methods: Long-Polling (long-polling) and streaming ). In this article, the demo is implemented based on streaming, and the front end uses a hidden IFRAME, which is also a common method. However, the progress on the browser is always changing due to the use of the IFRAME stream. This is because the IFRAME is always loading. Do not care about these details first.

Tomcat provides comet-related APIs. Using servlet to implement the cometprocessor interface can easily implement comet.

1. Preparations

1.1 first, you must configure the Tomcat connection to NiO. Otherwise, Tomcat comet cannot be used.

In the conf/server. xml directory of Tomcat, the Protocol is changed to org. Apache. Coyote. http11.http11nioprotocol:

<Connector connectiontimeout = "20000" Port = "8080" protocol ="Org. Apache. Coyote. http11.http11nioprotocol"Redirectport =" 8443 "/>

After configuration, start Tomcat as follows:

1.2. Tomcat's Catalina. jar package must be used during the development process, under the Tomcat lib directory. When the program runs in Tomcat, remove it.

2. Java background

2.1. cometservlet

This servlet is a servlet that processes comet HTTP persistent connections. this servlet implements the cometprocessor interface provided by Tomcat and uses the event method to process multiple events in the HTTP persistent connection cycle:

Begin event: There is a new HTTP connection;
End event: the connection is closed, for example, the browser is closed;
Error Event: Connection error, such as timeout.

Events are described in more detail in the official Tomcat documentation with:

Public class cometservlet extends httpservlet implements cometprocessor {// All HTTP persistent connections waiting for response private arraylist 

In this servlet, arraylist

When the servlet initializes init, it starts a thread to process chat messages and passes connections over.

In the begin event, a string with a length greater than 1024 is output through the response output stream, which is due to the browser cache, if not, Some browsers will wait until the stream is written to a certain number of bytes before it is displayed. This string has no practical significance, so you can write anything at will, but do not forget to add HTML comments.

2.2. messagesender

Messagesender is a thread that processes chat messages and implements the runnable interface. When new chat information is available, it immediately sends the information to all connected clients through the output stream of httpservletresponse. If no new information is available, it is blocked.

The blocking queue arrayblockingqueue in Java. util. Concurrent is used to process chat messages. The arrayblockingqueue. Take () method is used to obtain and remove an element from the queue. When the queue is empty, this method blocks the current thread until other threads add new elements to the queue. Of course, wait/notify can also be used here.

In fact, it can be understood as a producer consumer problem. When a user sends a message to the server, it is equivalent to producing a message, and this thread sends the message to the user, which is equivalent to consuming a message, this blocking queue is a buffer zone.

Public class messagesender implements runnable {// All HTTP persistent connections waiting for response private arraylist 

2.3. ajaxmessageservlet

This servlet is used to process the user's request for sending information. This is a common HTTP request rather than a persistent connection. When you click the "send" button on the page, the chat information will be submitted to the servlet through Ajax.

When receiving a new message, add a data entry to put in the blocked queue arrayblockingqueue in messagesender. When there is new data and the queue is not empty, the messagesender thread is no longer blocked and will immediately send the message to the client browser. This is equivalent to notifying the messagesender thread to send a message to the client.

Public class ajaxmessageservlet extends httpservlet {public void dopost (httpservletrequest request, httpservletresponse response) throws unsupportedencodingexception {request. setcharacterencoding ("UTF-8"); try {// This is equivalent to notifying the messagesender thread to send messages to the client messagesender. messages. put ("[" + request. getparameter ("name") + "]:" + request. getparameter ("MSG");} catch (interruptedexception e) {e. printstacktrace () ;}} public void doget (httpservletrequest request, httpservletresponse response) throws unsupportedencodingexception {dopost (request, response );}}

3. Web Front-end

<! Doctype HTML> 

In JS, The addmsg function is provided to the JS Script output in messagesender to call and display messages on the page.

The sendmsg function is a "send" button click event that sends the chat information to ajaxmessageservlet.

The iframerefresh function reload the IFRAME when the server times out. The timeout function times out for the server and the load is complete for the client. Therefore, it is called in the onload of the IFRAME. You can set the timeout time to use the event in the begin event. setTimeout (30*1000) or event. gethttpservletrequest (). setattribute ("org. apache. tomcat. comet. timeout ", new INTEGER (30*1000.

IFRAME on the page is set to display: none, that is, it is not displayed. SRC is the URL corresponding to cometservle. When there is new information, messagesender will output a piece of js to IFRAME:

Out. println ("<SCRIPT> parent. addmsg ('" + message + "<br>') </SCRIPT> ");

After the browser loads this JavaScript code, it will run immediately and call the addmsg function to display the information on the page.

4. Source Code

If you need the demo source code, leave email in the reply.

Cross brother reprint please indicate the source:

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: 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.