Synchronize the original text to http://www.waylau.com/mina-chat/
In the MINA QuickStart article, we show you how to use MINA to quickly build a time server. In the "Netty realization chat function" Article, we also introduced how to use Netty to implement the chat function. Since MINA and Netty are the same author, the architecture is similar, if you master one of them, learning another is not a difficult task. Now we use MINA to implement the chat function.
Get ready
- JDK 7+
- Maven 3.2.x
- MINA 2.x
- Eclipse 4.x
Service side
Let's start with the implementation of the handler (processor), handler is generated by MINA to handle I/O events, and the processor inherits from Iohandleradapter.
Simplechatserverhandler.java
public class Simplechatserverhandler extends Iohandleradapter {//(1) Private final set<iosession> sessions = Co Llections. Synchronizedset (New hashset<iosession> ()); (2) @Override public void sessioncreated (Iosession session) throws Exception {//(3) Sessions.add (session ); Broadcast ("has join the chat", session); } @Override public void sessionclosed (Iosession session) throws Exception {//(4) Sessions.remove (session); Broadcast ("Have left the chat", session); } @Override public void messagereceived (iosession session, Object message) throws Exception {//(5) String str = message.tostring (); Broadcast (str, session); } @Override public void Sessionidle (iosession session, Idlestatus status) throws Exception {//(6) System.out.println ("[Server] IDLE" + session.getremoteaddress () + session.getidlecount (status)); } @Override public voidExceptioncaught (iosession session, Throwable Cause) {cause.printstacktrace ();//(7) System.out.println ("[Se RVer] Client: "+ session.getremoteaddress () +" exception "); If an uncaught exception is encountered, the connection Session.close (true) is closed; /** * Broadcast Message * * @param message * * private void Broadcast (String message, iosession exceptsession) {//(8) synchronized (sessions) {for (iosession session:sessions) {if (session.isconn Ected ()) {if (Session.equals (exceptsession)) {Session.write ("[You]" + message) ; } else {session.write ("[Client" + session.getremoteaddress () + "]" + message); } } } } }}
1.SimpleChatServerHandler inherits from Iohandleradapter, this class implements the Iohandler interface, Iohandleradapter provides many interface methods for event handling, and then you can override these methods. Now it is only necessary to inherit the Iohandleradapter class instead of implementing the interface method yourself.
2. Set<IoSession> sessions
used to store all connections on the session.
3. Overwrite the sessioncreated () event handling method. Whenever a new client connection is received from the server, the client's iosession is deposited into the sessions list and the other clients in the list are notified Iosession
4. Overwrite the sessionclosed () event handling method. Whenever a client disconnects from the server, the client iosession from the sessions list and notifies other clients in the list iosession
5. Overwrite the messagereceived () event handling method. Broadcasts information to other clients ' iosession whenever the client writes information from the server.
6. Overwrite the Sessionidle () event handling method. Service end to hear client idle situation
The 7.exceptionCaught () event processing method is called when a Throwable object occurs, that is, when MINA due to an IO error or when the processor throws an exception while processing an event. In most cases, the caught exception should be recorded and the associated iosession be closed off. However, this approach can be handled differently when encountering different exceptions, such as a response message that you might want to send an error code before closing the connection.
8.broadcast () How the server is used for broadcasting
Simplechatserver.java
Write a main () method to start the server.
public class SimpleChatServer { public static void main(String[] args) { int port; if (args.length > 0) { port = Integer.parseInt(args[0]); } else { port = 8080; } SocketAcceptor acceptor = new NioSocketAcceptor(); // (1) acceptor.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new TextLineCodecFactory( Charset.forName( "UTF-8" )))); // (2) acceptor.setHandler(new SimpleChatServerHandler()); // (3) acceptor.getSessionConfig().setReadBufferSize(2048); // (4) acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 100);// (5) try { acceptor.bind(new InetSocketAddress(port)); // (6) } catch (IOException e) { e.printStackTrace(); } System.out.println("[Server]Listening on port " + port); }}
1.NioSocketAcceptor TCP/IP-based socket connection.
2.ProtocolCodecFilter is a chain of encoded and decoded filters that converts a connected bytebuffer into a message POJO and vice versa. While Textlinecodecfactory is a codec provided by MINA, it is easy to handle text-based protocols.
3. Set the Simplechatserverhandler created prior to the processor.
4. Session configuration, set the byte cache size.
5. Session configuration, set idle time.
6. All that is left is to bind the port and start the service. Here we bind the 8080 ports on the machine to all the cards on the machine by default.
Congratulations! You have completed the MINA Chat Service-based program.
Client Simplechatclienthandler.java
The client's processing class is relatively simple, just to print out the read information
public class SimpleChatClientHandler extends IoHandlerAdapter { @Override public void messageReceived(IoSession session, Object message) { String str = message.toString(); System.out.println(str); }}
Simplechatclient.java
Write a main () method to start the client.
public class Simplechatclient {private static final long connect_timeout = 1000L;//30 seconds; private static final String HOSTNAME = "127.0.0.1"; private static final int PORT = 8080; /** * @param args */public static void main (string[] args) {niosocketconnector connector = new Niosock Etconnector (); (1) Connector.setconnecttimeoutmillis (connect_timeout); Connector.getfilterchain (). AddLast ("Codec", new Protocolcodecfilter (New Textlinecodecfactory (charset.fo Rname ("UTF-8"))); Connector.sethandler (New Simplechatclienthandler ()); Iosession session; Connectfuture future = Connector.connect (new inetsocketaddress (HOSTNAME, PORT)); (2) future.awaituninterruptibly (); Session = Future.getsession (); while (true) {try {BufferedReader in = new BufferedReader (new InputStreamReader (system.in)); Session.write (In.readline ()); } catch (IOException e) {e.printstacktrace (); } } }}
1.NioSocketConnector for TCP/IP connectivity
2. Connect to the specified server
Run effect
Run Simplechatserver First, then run multiple simplechatclient, console input text continue testing
Source
See Https://github.com/waylau/apache-mina-2-user-guide-demos.simplechat
Reference
- Apache MINA 2 User Guide Https://github.com/waylau/apache-mina-2.x-user-guide
- Netty 4.x User Guide Https://github.com/waylau/netty-4-user-guide
MINA Realization Chat function