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

📄 quoteserver.java

📁 21天学通java的示例程序源代码
💻 JAVA
字号:
package com.wrox.quote;

import java.net.*;
import java.util.*;
import java.util.regex.*;
import java.io.*;

import java.nio.*;
import java.nio.charset.*;
import java.nio.channels.*;
import java.nio.channels.spi.*;

public class QuoteServer
{
    // Define a default port
    private static final int DEFAULT_PORT = 7236;

    // Pattern used to parse the quotes.txt file into lines.
    private static Pattern linePattern = Pattern.compile(".*\r?\n");

    /* This must be a member variable so that we can close it
       in the classes finalizer method. */
    private FileChannel fileChannel;

    /* The buffer that will be associated with the fileChannel
       to hold the quote.txt data. */
    private CharBuffer quotes;

    /* The number of lines / 2 since a quote consists of
     a line for the quote and a line for the author.*/
    private int numberOfQuotes;
    
    public QuoteServer() throws IOException {
        init();
    }

    /* Map the quote file into a charBuffer.
       For a large scale implementation you'd want to use a more
       scalable solution such a relational database.*/
    private void init() throws IOException
    {
        /* Open the file using FileInputStream and get a channel
           from the input stream. */
        FileInputStream fis = new FileInputStream( "quotes.txt" );
        fileChannel = fis.getChannel();

        // Map the file in memory for speedy access.
        int size = (int)fileChannel.size();
        MappedByteBuffer buffer = fileChannel.map( FileChannel.MAP_RO,0, size );

        /* Decode the byte buffer into a character buffer. We'll
           use the HTML standard Latin 1 character set. */
        Charset charset = Charset.forName("ISO-8859-1");
        CharsetDecoder decoder = charset.newDecoder();
        quotes = decoder.decode( buffer );

        /* Determine the number of quotes in the file for
         future reference. */
        Matcher matcher = linePattern.matcher( quotes );
        for( numberOfQuotes = 0; matcher.find(); numberOfQuotes++ )
        {
            // empty loop since we are just counting lines.
        }

        /* Because each quote has an associated author on the next line,
        divide this number by 2*/
        numberOfQuotes /= 2;
    }

    /* This method is the actual server that listens, accepts
       and responds to client requests. */
    public void listen( int port ) throws Exception
    {

        System.out.println( "Quote Server listening on port " + 
                             port + "." );

        // Create a non-blocking server socket
        ServerSocketChannel serverChannel = ServerSocketChannel.open();
        serverChannel.configureBlocking( false );

        // Use the host and port to bind the server socket
        InetAddress inetAddress = InetAddress.getLocalHost();
        InetSocketAddress socketAddress = new InetSocketAddress( 
                                              inetAddress, port );
        serverChannel.socket().bind( socketAddress );

        // The Selector for incoming requests
        Selector requestSelector = SelectorProvider.provider().
                                   openSelector();

        /* Put the server socket on the selectors 'ready list'.
           No need to retain the SelectionKey returned. */
        serverChannel.register( requestSelector, SelectionKey.OP_ACCEPT );

        /* In the while loop, any of registered operation will
           be returned the select() method. The select() method itself
           will block until a channel is ready. */
        while ( requestSelector.select() > 0 )
        {
            System.out.println( "Connection Accepted..." );

            //A request has been made and is ready for I/O.
            Set requestKeys = requestSelector.selectedKeys();

            Iterator iterator = requestKeys.iterator();
            while( iterator.hasNext() )
            {
                SelectionKey requestKey = (SelectionKey) iterator.next();
                
                // Get the socket that's ready for I/O
                ServerSocketChannel requestChannel = (ServerSocketChannel)
                                                      requestKey.channel();
                // This shouldn't block
                Socket requestSocket = requestChannel.accept();

                // Send a quote to the client
                PrintWriter out = new PrintWriter( 
                                      requestSocket.getOutputStream(), 
                                      true );
                out.println( getNextQuote() );
                out.close();

                iterator.remove();
            }
        }
    }

    // Show off a bit of the NIO classes and get a random quote.
    private String getNextQuote()
    {
        // Select a number from 0 to the max number of quotes.
        int quoteIndex = (((int) (Math.random() * 
                            numberOfQuotes)) * 2 );;

        // Iterate through the quotes up until quoteIndex;
        Matcher matcher = linePattern.matcher( quotes );
        for( int i=0; matcher.find() && i<quoteIndex; i++ )
        {
            // empty loop since we are just counting lines.
        }

        // The next two matched (line) are the quote that we want.
        String quote = matcher.group().trim();
        matcher.find();
        quote += "\n" + matcher.group().trim();

        return quote;
    }

    // Make sure that we close our FileChannel.
    protected void finalize() throws Throwable
    {
        try
        {
            fileChannel.close();
        }
        finally
        {
            super.finalize();
        }
    }

    public static void main(String[] args)
    {
        int port = DEFAULT_PORT;

        if( args.length > 0 )
        {
            try
            {
                port = Integer.parseInt( args[0] );
            }
            catch( NumberFormatException nfe )
            {
                System.err.println( "Syntax: java QuoteServer [port " +
                                    "number to accept connections on.]" );
                System.exit( 1 );
            }
        }

        try
        {
            new QuoteServer().listen( port );
        }
        catch( Exception e )
        {
            System.err.println( "Error: " + e );
        }
    }
}

⌨️ 快捷键说明

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