Socket programming and Mina framework simple example __ programming

Source: Internet
Author: User
Tags flush readline throwable

To implement a long connection between the client and the server, you can connect the server to the client by using the socket. In this article, you will implement the server side and client of the socket in a native way, and then implement it again with the Mina framework.
Native:
The client can be implemented as follows:
Socketclient:

Package socketclient;
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.io.OutputStreamWriter;

Import Java.net.Socket;
    public class Socketclient {public int port = 9898;

    Public String hostaddress = "127.0.0.1";
        public static void Main (string[] args) {socketclient client = new Socketclient ();
    Client.start ();
        private void Start () {BufferedReader inputreader = null;
        OutputStreamWriter output = null;
        Socket socket = NULL;
            try {socket = new socket (hostaddress, port);
            Inputreader = new BufferedReader (new InputStreamReader (system.in));
            Output = new OutputStreamWriter (Socket.getoutputstream ());
            String inputcontent;
            int count = 0; while (!) (
                    Inputcontent = Inputreader.readline ()). Equals ("Bye")) {output.write (inputcontent);
               Output.write ("\ n"); Output.flush ();
            GETSERVERMSG (socket);
        } catch (IOException e) {e.printstacktrace ();
                Finally {try {output.close ();
                Inputreader.close ();
            Socket.close ();
            catch (IOException e) {e.printstacktrace (); }} private void getservermsg (socket socket) {New Thread (new Runnable () {@Overri
                De public void Run () {BufferedReader reader = null; try {reader = new BufferedReader (New InputStreamReader (socket.getinputst
                    Ream ()));
                    String servermsg;
                    while ((servermsg = Reader.readline ())!= null) {System.out.println ("Server say:" + servermsg);
  } catch (IOException e) {e.printstacktrace ();              Finally {try {reader.close ();
                    catch (IOException e) {e.printstacktrace ();
    }}}). Start ();
 }
}

Server-side:

Package Com.socket.tra;
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.io.OutputStreamWriter;
Import Java.net.ServerSocket;

Import Java.net.Socket; public class Socketserver {public static void main (string[] args) {socketserver server = new Socketserver ()
        ;
    Server.startserver ();
        private void StartServer () {ServerSocket serversocket = null;
        Socket socket = NULL;
            try {serversocket = new ServerSocket (9898);
                while (true) {socket = serversocket.accept ();
                System.out.println (Socket.hashcode () + "is Connect");
            Connect (socket);
        } catch (IOException e) {e.printstacktrace (); } private void connect (final socket socket) {New Thread (new Runnable () {public void run (
                {BufferedReader reader = null; OutpuTstreamwriter writer = null; try {reader = new BufferedReader (New InputStreamReader (socket.getinputst
                    Ream ()));
                    writer = new OutputStreamWriter (Socket.getoutputstream ());
                    String msg;
                        while (msg = Reader.readline ())!= null) {System.out.println (Socket.hashcode () + "say:" +msg);
                        Writer.write (msg + "\ n");
                    Writer.flush ();
                } catch (IOException e) {e.printstacktrace ();
                        Finally {try {writer.close ();
                        Reader.close ();
                    Socket.close ();
                    catch (IOException e) {e.printstacktrace ();
    }}}). Start ();
 }

}

This is the basic usage of sockets, but in practice we typically use encapsulated frameworks, and Apache Mina is the framework that can help users develop high-performance and highly scalable network applications. It provides an abstract, event-driven, asynchronous API through the Java NIO technology based on the TCP/IP and UDP/IP protocols.
specific usage can go to the official website to understand, here provides a simple use example, realizes with the above native method the same function.
Version One:
Server-side:

Package com.socket;

Import java.io.IOException;
Import java.net.InetSocketAddress;
Import Org.apache.mina.filter.codec.ProtocolCodecFilter;
Import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
Import Org.apache.mina.transport.socket.nio.NioSocketAcceptor;

public class Main {public
    static int port = 9898;
    public static void Main (string[] args) {

        Niosocketacceptor acceptor = new Niosocketacceptor ();

        try {
            //Set handler
            Acceptor.sethandler (new MyHandler ());
            Set filter
            Acceptor.getfilterchain (). AddLast ("Codec", new Protocolcodecfilter (New Textlinecodecfactory ());
            Bind port number
            acceptor.bind (new inetsocketaddress (port);

        } catch (IOException e) {
            e.printstacktrace ();
        }
    }

}

MyHandler:

Package com.socket;
Import Org.apache.mina.core.service.IoHandler;
Import Org.apache.mina.core.session.IdleStatus;

Import org.apache.mina.core.session.IoSession;
            public class MyHandler implements Iohandler {public void Exceptioncaught (Iosession arg0, Throwable arg1)
    Throws Exception {System.out.println ("Exception");
    The public void inputclosed (Iosession arg0) throws Exception {System.out.println ("inputclosed");
        } public void messagereceived (Iosession arg0, Object arg1) throws Exception {String msg = (string) arg1;
        SYSTEM.OUT.PRINTLN ("messagereceived server:" + msg);
    Arg0.write (msg);
    public void Messagesent (Iosession arg0, Object arg1) throws Exception {System.out.println ("messagesent"); public void sessionclosed (Iosession arg0) throws Exception {System.out.println ("sessionclosed" +arg0.h
    Ashcode ()); } public void sessioncreated (Iosession arg0) throws Exception {System.out.println ("sessioncreated" +arg0.hashcode ());  public void Sessionidle (Iosession arg0, Idlestatus arg1) throws Exception {System.out.println ("Sessionidle
    "+arg0.hashcode () +", "+arg1"; public void sessionopened (Iosession arg0) throws Exception {System.out.println ("sessionopened" +ARG0.HASHC
    Ode ());
 }

}

Client:

Package Socketclient.mina;
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.io.OutputStreamWriter;
Import java.net.InetSocketAddress;

Import Java.net.Socket;
Import Org.apache.mina.core.future.ConnectFuture;
Import org.apache.mina.core.session.IoSession;
Import Org.apache.mina.filter.codec.ProtocolCodecFilter;
Import Org.apache.mina.filter.codec.textline.TextLineCodecFactory;

Import Org.apache.mina.transport.socket.nio.NioSocketConnector;
    public class Socketclient {public int port = 9898;

    Public String hostaddress = "127.0.0.1"; public static void Main (string[] args) throws IOException {niosocketconnector connector = new Niosocketconnector
        ();
        Connector.sethandler (New Myclienthandler ());
        Connector.getfilterchain (). AddLast ("Codec", new Protocolcodecfilter (New Textlinecodecfactory ());
        Connectfuture future = Connector.connect (New inetsocketaddress ("127.0.0.1", 9898)); Future. awaituninterruptibly ()//Waiting for connection iosession session = Future.getsession ();
        BufferedReader inputreader = new BufferedReader (new InputStreamReader (system.in));
        String inputcontent; while (!) (
        Inputcontent = Inputreader.readline ()). Equals ("Bye")) {session.write (inputcontent);
 }

    }


}

Myclienthandler:

Package Socketclient.mina;
Import Org.apache.mina.core.service.IoHandler;
Import Org.apache.mina.core.session.IdleStatus;

Import org.apache.mina.core.session.IoSession;
            public class Myclienthandler implements Iohandler {public void Exceptioncaught (Iosession arg0, Throwable arg1)
    Throws Exception {System.out.println (Arg1.getcause ());
    public void inputclosed (Iosession arg0) throws Exception {//System.out.println ("inputclosed");
        } public void messagereceived (Iosession arg0, Object arg1) throws Exception {String msg = (string) arg1;
    SYSTEM.OUT.PRINTLN ("Client messagereceived:" + msg); public void Messagesent (Iosession arg0, Object arg1) throws Exception {System.out.println ("client MessageS
    Ent-> "+ (String) arg1); public void sessionclosed (Iosession arg0) throws Exception {System.out.println ("sessionclosed" +ARG0.HASHC
    Ode ()); } public void sessioncreated (Iosession arg0) throws Exception {System.out.println ("sessioncreated" +arg0.hashcode ());  public void Sessionidle (Iosession arg0, Idlestatus arg1) throws Exception {System.out.println ("Sessionidle
    "+arg0.hashcode () +", "+arg1"; public void sessionopened (Iosession arg0) throws Exception {System.out.println ("sessionopened" +ARG0.HASHC
    Ode ()); }

}

Version one uses the framework written textlinecodecfactory to parse strings, in practical applications, often to customize the parsing function, so version two write a string parsing function.
Version two:
Server side:
Main: primary function
Mydecoder: Implementing Data decoding
Myencoder: Implementing Data encoding
MyHandler:
Myprotocolfactory: Generating encodings and decoders
Mycumulativeencoder: Implementation of data encoding, server data can be cached to prevent data loss

Main:

Package com.socket.r1;
Import java.io.IOException;

Import java.net.InetSocketAddress;
Import Org.apache.mina.core.session.IdleStatus;
Import Org.apache.mina.filter.codec.ProtocolCodecFilter;
Import Org.apache.mina.filter.codec.textline.TextLineCodecFactory;
Import Org.apache.mina.filter.logging.LoggingFilter;

Import Org.apache.mina.transport.socket.nio.NioSocketAcceptor;
    public class Main {public static int port = 9898;

        public static void Main (string[] args) {Niosocketacceptor acceptor = new Niosocketacceptor ();
            try {acceptor.sethandler (new MyHandler ());
            Acceptor.getfilterchain (). AddLast ("Logger", New Loggingfilter ());
            Acceptor.getfilterchain (). AddLast ("Codec", new Protocolcodecfilter (New Myprotocolcodecfactory ());
            Acceptor.getsessionconfig (). Setidletime (Idlestatus.both_idle, 125);     

        Acceptor.bind (New Inetsocketaddress (port)); catch (IOException e) {e.printstacktrace (); }
    }

}

Mydecoder:

Package com.socket.r1;
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; public class Mydecoder implements Protocoldecoder {public void decode (Iosession sessions, Iobuffer in, Protocoldecode
        Routput output) throws Exception {//record character stream read position int startposition = In.position ();
            while (In.hasremaining ()) {byte b = in.get ();
                if (b = = ' \ n ') {int curposition = in.position ();
                The last position of the record character stream is int limit = In.limit ();
                Sets the read pointer to the initial position in.position (startposition);
                Sets the end position to the current read position in.limit (curposition);
                Iobuffer buf = In.slice ();
                byte[] bytes = new Byte[buf.limit ()];
                Putting the intercepted content into the bytes array buf.get (bytes); String str = new String (bytes);
                Output.write (str);
                In.position (curposition);
            In.limit (limit); }} public void Dispose (Iosession arg0) throws Exception {System.out.println ("dispose" + arg0.

    Hashcode ()); public void Finishdecode (Iosession arg0, Protocoldecoderoutput arg1) throws Exception {System.
    Out.println ("Finishdecode" + Arg0.hashcode ()); }

}

Myencoder:

Package com.socket.r1;
Import Java.nio.charset.Charset;

Import Java.nio.charset.CharsetEncoder;
Import Org.apache.mina.core.buffer.IoBuffer;
Import org.apache.mina.core.session.IoSession;
Import Org.apache.mina.filter.codec.ProtocolEncoder;

Import Org.apache.mina.filter.codec.ProtocolEncoderOutput; public class Myencoder implements Protocolencoder {public void Dispose (Iosession arg0) throws Exception {Sy    
    Stem.out.println ("Dispose" + arg0.hashcode ());

        } public void Encode (iosession arg0, Object msg, protocolencoderoutput output) throws Exception {
        String s= null;
        if (msg instanceof string) {s = (string) msg;
            } if (s!=null) {Charsetencoder Charsetencoder = (charsetencoder) arg0.getattribute ("encoder");
                if (Charsetencoder ==null) {charsetencoder = Charset.defaultcharset (). Newencoder ();
            Arg0.setattribute ("encoder", charsetencoder);
       }     Iobuffer Iobuffer = Iobuffer.allocate (s 

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.