⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 hellolistener.java

📁 javaP2P技术内幕课程0789的源代码
💻 JAVA
字号:
import org.beepcore.beep.core.*;
import org.beepcore.beep.profile.Profile;
import org.beepcore.beep.profile.ProfileConfiguration;
import org.beepcore.beep.profile.echo.EchoProfile;
import org.beepcore.beep.transport.tcp.AutomatedTCPSessionCreator;
import org.beepcore.beep.transport.tcp.TCPSession;
import java.io.BufferedReader;
import java.io.InputStreamReader;


/**
*This is a BEEP Peer which listens for an incoming
*request.The port and profile string are defined
*by the constants.The peer also send back a response to the
*initiator of the message that it receives.
*/
public class HelloListener {
    //Port number that is used
    public static final int PORT = 8888;

    //This string is a URI that represents the profile.
    public static final String PROFILE_STRING = "http://testdomain.com/test";

    //private variable to check if the application can exit
    private static boolean exit = false;

    /**
    *The main method creates an instance of the HelloListener.
    *The listener is made to listen for incoming messages.
    */
    public static void main(String[] args) throws Exception {
        new HelloListener().listenForInitiator();
    }

    /**
    *The method listens for a TCP Session to be initiated by
    *the initiator.Once a session is obtained the method exits
    *after a sleep interval.
    *
    */
    public void listenForInitiator() {
        log("Starting to Listen on port " + PORT);

        //create a new ProfileRegistry
        ProfileRegistry registry = new ProfileRegistry();

        //Add a StartChannelListener to the registry.
        //This listener will contain logic to manage
        //starting and stopping of channels.
        //In this case we use the HelloProfile to
        //get an instance of the HelloChannelListener.
        try {
            registry.addStartChannelListener(PROFILE_STRING, 
                                             new HelloProfile().init(
                                                     PROFILE_STRING, null), 
                                             null);
        } catch (BEEPException beepException) {
            //This means that creating a profile failed
            //The listener should be exited
            exit = true;
        }

        //continue till the exit flag is true.
        while (!exit) {
            try {
                //Get a TCPSession.
                //This is a blocking call.
                TCPSession session = AutomatedTCPSessionCreator.listen(PORT, 
                                                                       registry);


                //sleep for a small delay.
                //This ensures consistency of output.
                Thread.sleep(2000);
            } catch (BEEPException beepException) {
                //This means that the application is not
                //able to listen properly
                //Try to abort.
                log("Unable to listen Message is : " + 
                    beepException.getMessage());
                exit = true;
            } catch (InterruptedException excp) {
                //No OP
            }
        }

        log("Exiting...");
    }

    /**
    *A simple Beep profile which implements the
    *<code>Profile</code>interface.
    *
    */
    class HelloProfile implements Profile {
        /**
        *Initializes the profile and returns an appropriate
        *<code>StartChannelListener</code>.
        *
        */
        public StartChannelListener init(String uri, 
                                         ProfileConfiguration config)
                                  throws BEEPException {
            return new HelloChannelListener();
        }
    }

    /**
    *A Listener implementing the <code>StartChannelListener</code>
    *interface.It contains logic for managing the start and stop
    *events in a given channel.
    */
    class HelloChannelListener implements StartChannelListener {
        /**
        *Callback method that determines if a profile can be advertised.
        *If there are any prerequisites for a profile,they must be checked
        *here.Only
        *
        */
        public boolean advertiseProfile(Session session)
                                 throws BEEPException {
            return true;
        }

        /**
        *Called when a new channel is started.
        *
        */
        public void startChannel(Channel channel, java.lang.String encoding, 
                                 java.lang.String data)
                          throws StartChannelException {
            //create a new data listener for this channel.
            channel.setDataListener(new HelloDataListener());
        }

        /**
        *Called before a channel is closed.
        */
        public void closeChannel(Channel channel) throws CloseChannelException {
            //reset the data listener
            channel.setDataListener(null);


            //reset the application context
            channel.setAppData(null);
        }
    }

    /**
    *A Message listener which gets notified whenever
    *any message is received.It implements the
    *<code>MessageListener</code>interface.
    */
    class HelloDataListener implements MessageListener {
        /**
        *Receives a BEEP message.
        */
        public void receiveMSG(Message message) throws BEEPError, 
                                                       AbortChannelException {
            try {
                //Get a data stream from the message.
                DataStream stream = message.getDataStream();

                //Create a buffered reader for reading the data.
                BufferedReader reader = new BufferedReader(
                                                new InputStreamReader(
                                                        stream.getInputStream()));


                //Print the recieved message to console.
                log("Message from initiator = > " + reader.readLine());


                //Close the reader
                reader.close();


                //Send a reply to the initiator of the message
                log("Sending a reply to initiator...");
                message.sendRPY(new StringDataStream(" Hello Initiator !"));


                //exit the application
                exit = true;
            } catch (java.io.IOException excp) {
                log("Message from Exception : " + excp.getMessage());
                throw new AbortChannelException(excp.getMessage());
            } catch (BEEPException beepExcp) {
                log("Message from Exception : " + beepExcp.getMessage());
                throw new AbortChannelException(beepExcp.getMessage());
            }
        }
    }

    //private method to log messages to console
    private static void log(String message) {
        System.out.println(message);
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -