开发者

Socket Server with multiple client in java

I have to create a socket server which will listen to multiple client. Suppose there are 6 clients connected to the server at the same time and each of the clients are sending some commands to server at the same time. If these clients sending the message to server for every 1 second how can I handle the those messages from the 6 clients on the server side to store it in the table and the acknowledgement t开发者_JS百科o each client.

How can i handle these input from from the client. Whether I have to create 6 threads to handle these inputs from the client.

Please give me a idea to approach this issue.


Create a new thread per client connection and continually do a blocking read on the streams in each thread to look for data to process.

class Server {

    ClientThread    threads[];
    int             size;
    ServerSocket    serverSocket;
    boolean         active;

    Server() throws Exception {
        /* initialize connection */
        active = true;
        listen();
    }

    void listen() throws Exception {
        while ( active ) {
            Socket clientSocket = serverSocket.accept();
            threads[ size++ ] = new ClientThread( clientSocket );
            threads[ size - 1 ].start();
        }
    }
}

class ClientThread extends Thread {

    OutputStream    out;
    InputStream     in;
    boolean         active;

    ClientThread( Socket clientSocket ) throws Exception {
        out = clientSocket.getOutputStream();
        in = clientSocket.getInputStream();
    }

    public void run() {
        active = true;
        while ( active ) {
            listen();
        }
    }

    private void listen() {
        try {
            int res = process( in.read() );
            out.write( res );
        } catch ( Exception e ) {}
    }

    private int process( int b ) {
        return -1;
    }
}


Any reason you can't use a servlet container to do this? This is 10 lines of code in a Servlet + Tomcat/Jetty.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜