Apache MiNa realizes multi-person chat room

Source: Internet
Author: User
Tags sessions log4j
Apache MiNa realizes multi-person chat room

Development environment:

System:windows

javasdk:1.6

Ide:eclipse, MyEclipse 6.6

To develop a dependent library:

jdk1.4+, Mina-core-2.0.4.jar, Slf4j-api-1.5.11.jar, Slf4j-log4j12-1.5.11.jar

Email:hoojo_@126.com

Blog:http://blog.csdn.net/ibm_hoojo

http://hoojo.cnblogs.com/

Http://hoojo.blogjava.net

Recently used socket to write the chat program, mainly mobile phone program through the socket to connect the server side of the ServerSocket, and then the server to send over the client according to the unified standard message. The resolution is then forwarded to the OpenFire server using the smack framework, and the OpenFire server sends chat information to the client program.

The socket server has recently been found to consume a large resource. I am using blocking multi-threaded communication, this way will cause a lot of waste of server resources, long-term occupation of the server's CPU scheduling power, and a long time to block the program, waiting for clients to connect, send messages, and so on.

In order to solve the above situation, Apache Mina can solve this problem very well. Mina uses a non-blocking, single-threaded, NiO communication method.

The idea of non-blocking communication is to have one thread do multiple things at the same time, and this thread will use the free time to complete this matter to do another thing, and not be idle for a moment. This thread will also constantly monitor the occurrence of everything that needs to be handled, one at a time, and then continue to monitor the individual events. First, introduce

First of all, Mina is something. Look at the official website (http://mina.apache.org/) for its explanation:

The Apache Mina (Multipurpose infrastructure networked applications) is a network application framework that can help users develop high-performance and highly scalable network applications; It provides an abstract, Event-driven asynchronous APIs that enable Java NiO to develop quickly and efficiently under a variety of transport protocols, such as the TCP/IP,UDP/IP protocol.

Apache Mina is also known as:

nio Framework

 Network sockets (Networking Sockets) class Library

 Event-driven asynchronous APIs (note: Asynchronous APIs are also added in JDK7)

In short: we simply understand that it is a communication framework that encapsulates the underlying IO operation and provides advanced operational APIs. second, server-side coding work

First step:

Using the Apache Mina Framework, you need to download the jar

Download Address: Http://mina.apache.org/dyn/closer.cgi/mina/2.0.4/apache-mina-2.0.4-bin.zip

You need to add the jar below

If you use a log, you need to add a log configuration file log4j.properties

Step Two:

Write the decoding factory and encoder, decoder class to be used for communication, as follows

Package com.hoo.mina.code.factory;
Import org.apache.mina.core.session.IoSession;
Import Org.apache.mina.filter.codec.ProtocolCodecFactory;
Import Org.apache.mina.filter.codec.ProtocolDecoder;
Import Org.apache.mina.filter.codec.ProtocolEncoder;
Import Com.hoo.mina.code.CharsetDecoder;
Import Com.hoo.mina.code.CharsetEncoder;
/**
* <b>function:</b> character encoding, decoding factory class, coding filter Factory
* @author Hoojo
* @createDate 2012-6-26 01:08:50
* @file Charsetcodecfactory.java
* @package Com.hoo.mina.code.factory
* @project Apachemina
* @blog Http://blog.csdn.net/IBM_hoojo
* @email hoojo_@126.com
* @version 1.0
*/
public class Charsetcodecfactory implements Protocolcodecfactory {
    @Override
    Public Protocoldecoder Getdecoder (iosession session) throws Exception {
        return new Charsetdecoder ();
    }
    @Override
    Public Protocolencoder Getencoder (iosession session) throws Exception {
        return new Charsetencoder ();
    }
}

Decoding class

Package Com.hoo.mina.code;
Import Java.nio.charset.Charset;
Import Org.apache.log4j.Logger;
Import Org.apache.mina.core.buffer.IoBuffer;
Import org.apache.mina.core.session.IoSession;
Import Org.apache.mina.filter.codec.ProtocolDecoder;
Import Org.apache.mina.filter.codec.ProtocolDecoderOutput;
/**
* <b>function:</b> character decoding
* @author Hoojo
* @createDate 2012-6-26 11:14:18
* @file Charsetdecoder.java
* @package Com.hoo.mina.code
* @project Apachemina
* @blog Http://blog.csdn.net/IBM_hoojo
* @email hoojo_@126.com
* @version 1.0
*/
public class Charsetdecoder implements Protocoldecoder {
    Private final static Logger log = Logger.getlogger (Charsetdecoder.class);
    
    Private final static Charset Charset = Charset.forname ("UTF-8");    
    Variable Iobuffer data buffers
    Private Iobuffer buff = iobuffer.allocate. Setautoexpand (True);
    
    @Override
    public void decode (Iosession sessions, Iobuffer in, protocoldecoderoutput out) throws Exception {
        Log.info ("######## #decode #########");
        
        If there's a message
        while (In.hasremaining ()) {
            To judge whether the message is Terminator, the terminator of different platforms are not the same;
            The Windows newline character (\ r \ n) is considered a terminator of a full message; UNIX is \n;mac is \ r
            byte B = in.get ();
            if (b = = ' \ n ') {
                Buff.flip ();
                byte[] bytes = new Byte[buff.limit ()];
                Buff.get (bytes);
                String message = new String (bytes, charset);
                
                Buff = Iobuffer.allocate. Setautoexpand (True);
                
                If it's over, write the data after the transcoding.
                Out.write (message);
                Log.info ("message:" + message);
            } else {
                Buff.put (b);
            }
        }
    }
    @Override
    public void Dispose (Iosession session) throws Exception {
        Log.info ("######## #dispose #########");
        Log.info (Session.getcurrentwritemessage ());
    }
    @Override
    public void Finishdecode (Iosession sessions, protocoldecoderoutput out) throws Exception {
        Log.info ("######## #完成解码 #########");

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.