以下代码,1000个并发不能保证,不过1-2百个并发应该是没问题的.try {
ServerSock svrSock = new ServerSocket(PORT, BACKLOG);
while (isListen) {

Socket sock = svrSock.accept();
try
{
         // todo... 创建线程处理业务逻辑 }
catch (IOException e)
{
if (!sock.isClosed())
sock.close();
}
}
}
catch (IOException e) {
//...
}
finally {
try {
// 关闭侦听端口
svrSock .close();
} catch (IOException e) {}
}

解决方案 »

  1.   


    import java.nio.ByteBuffer;
    import java.nio.channels.ServerSocketChannel;
    import java.nio.channels.SocketChannel;
    import java.nio.channels.Selector;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.SelectableChannel;
    import java.net.Socket;
    import java.net.ServerSocket;
    import java.net.InetSocketAddress;
    import java.util.*;/**
    * Simple echo-back server which listens for incoming stream connections
    * and echoes back whatever it reads. A single Selector object is used to
    * listen to the server socket (to accept new connections) and all the
    * active socket channels.
    *
    * @author Ron Hitchens ([email protected])
    */public class SelectSockets
    {
        public static int PORT_NUMBER = 1235;
        public static Vector fd = new Vector() ;    public static void main (String [] argv) throws Exception
        {
    new SelectSockets( ).go (argv);
        }
        public void go (String [] argv) throws Exception
        {
    int port = PORT_NUMBER;
    if (argv.length > 0) { // Override default listen port
        port = Integer.parseInt (argv [0]);
    }
    System.out.println ("Listening on port " + port); // Allocate an unbound server socket channel
    ServerSocketChannel serverChannel = ServerSocketChannel.open( ); // Get the associated ServerSocket to bind it with
    ServerSocket serverSocket = serverChannel.socket( ); // Create a new Selector for use below
    Selector selector = Selector.open( ); // Set the port the server channel will listen to
    serverSocket.bind (new InetSocketAddress (port)); // Set nonblocking mode for the listening socket
    serverChannel.configureBlocking (false); // Register the ServerSocketChannel with the Selector
    serverChannel.register (selector, SelectionKey.OP_ACCEPT);
    SocketChannel channel = null ; while (true) {
        // This may block for a long time. Upon returning, the
        // selected set contains keys of the ready channels.
        int n = selector.select( );
        if (n == 0) {
    continue; // nothing to do
        }     // Get an iterator over the set of selected keys
        Iterator it = selector.selectedKeys().iterator( );     // Look at each key in the selected set
        while (it.hasNext( )) {
    SelectionKey key = (SelectionKey) it.next( );
    // Is a new connection coming in?
    if (key.isAcceptable( )) {
        ServerSocketChannel server =
    (ServerSocketChannel) key.channel( );
        channel = server.accept( );
        registerChannel (selector, channel,
         SelectionKey.OP_READ);
        sayHello (channel);
                        fd.add (channel) ; } // Is there data to read on this channel?
    if (key.isReadable( )) {
        System.out.println ("In readable" ) ;
        readDataFromSocket (key);
        registerChannel (selector, channel, SelectionKey.OP_WRITE);

    //     sayHello2( channel ) ;
    } // Remove key from selected set; it's been handled
    it.remove( );
        }
    }
        }
        // ----------------------------------------------------------
        /**
         * Register the given channel with the given selector for
         * the given operations of interest
         */
        protected void registerChannel (Selector selector,
        SelectableChannel channel, int ops)
    throws Exception
        {
    if (channel == null) {
        return; // could happen
    }
    // Set the new channel nonblocking
    channel.configureBlocking (false);
    // Register it with the selector
    channel.register (selector, ops);
        }
        // ----------------------------------------------------------
        // Use the same byte buffer for all channels. A single thread is
        // servicing all the channels, so no danger of concurrent acccess.
        private ByteBuffer buffer = ByteBuffer.allocateDirect (1024);
        /**
         * Sample data handler method for a channel with data ready to read.
         * @param key A SelectionKey object associated with a channel
         * determined by the selector to be ready for reading. If the
         * channel returns an EOF condition, it is closed here, which
         * automatically invalidates the associated key. The selector
         * will then de-register the channel on the next select call.
         */
        protected void readDataFromSocket (SelectionKey key)
    throws Exception
        {
    SocketChannel socketChannel = (SocketChannel) key.channel( );
    int count;
    buffer.clear( ); // Empty buffer
    // Loop while data is available; channel is nonblocking
    while ((count = socketChannel.read (buffer)) > 0) {
        buffer.flip( ); // Make buffer readable
        // Send the data; don't assume it goes all at once            for( int i = 0 ; i < fd.size() - 1 ; ++i )
                {
                    System.out.println( "i = " + i + ", size = " + (fd.size() - 1) ) ;
                    SocketChannel tempChannel = (SocketChannel)fd.get( i ) ;
            System.out.println ("Connected at port: " + tempChannel.socket().getPort() ) ;                if( tempChannel.isConnected() )
                    {/*
                       BufferedReader inFromClient =
                           new BufferedReader( new InputStreamReader(
                                   temp.getInputStream() ) ) ;                   // Return canned message
                       PrintWriter out = new PrintWriter
                         (temp.getOutputStream(), true);
                       out.print("Relay Message from other clients--");
                       out.println( "fromclient = " + inFromClient.readLine() ) ;
                       System.out.println( "HELLO\n" ) ;
    */            while (buffer.hasRemaining( )) {
           tempChannel.write (buffer);
               }
                       buffer.clear( ) ;//                   tempChannel.close() ;
                     }
       else
         fd.remove( i ) ;
                  }     // WARNING: the above loop is evil. Because
        // it's writing back to the same nonblocking
        // channel it read the data from, this code can
        // potentially spin in a busy loop. In real life
        // you'd do something more useful than this.
        
        buffer.clear( ); // Empty buffer
    } if (count < 0) {
        // Close channel on EOF, invalidates the key
        socketChannel.close( );
    }    }
        // ----------------------------------------------------------
        /**
         * Spew a greeting to the incoming client connection.
         * @param channel The newly connected SocketChannel to say hello to.
         */
        private void sayHello (SocketChannel channel)
    throws Exception
        {
    buffer.clear( );
    buffer.put ("Hi there!\r\n".getBytes( ));
    buffer.flip( );
    channel.write (buffer);
        }    private void echo (SocketChannel channel)
    throws Exception
        {
    buffer.clear( );
    buffer.put ("Hi there 2nd time!\r\n".getBytes( ));
    buffer.flip( );
    channel.write (buffer);
    buffer.clear( );// channel.close() ;
        }
    }
    这是一个NIO包写的ECHO服务端,应该能支持1000个连接。具体原理你可以看看NIO的介绍。
    http://java.sun.com/j2se/1.4.2/docs/guide/nio/