Java · Java8 · sample java server

Asynchronous Server In Java

The Asynchronous Server is  a sample server program which can handle 200 concurrent connections at a time.  The fixed thread pool which is used in this program can be increased to handle more request. However it may throw out of memory as more number of thread going to use more memory.

/**
 * This server socket program has been created to test the programe with -client and -server JVM parameters.
 */
package sockets;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author prabhu kvn
 *
 */
public class ServerSocketDemo {
	volatile int counter =0;
	/**
	 * 
	 */
	public ServerSocketDemo() {
		// TODO Auto-generated constructor stub
	}
	
	public static void main(String[] args) {
		ServerSocketDemo demo = new ServerSocketDemo();
		demo.startServer();
	}

	private void startServer() {
		// TODO Auto-generated method stub
		try {
			ExecutorService exeutorService = Executors.newFixedThreadPool(200);
			ServerSocket serverSocket = new ServerSocket(8181,10000);
			
			
			while(true) {
			Socket socket = serverSocket.accept();
			exeutorService.submit(()->{
				try {
					counter = process(socket);
				} catch (IOException | InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			});
			
			}
			//socket.close();
			
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	private int process(Socket socket) throws IOException, SocketException, InterruptedException {
		System.out.println("Server Socket:"+socket);
		OutputStream out = socket.getOutputStream();
		out.write(("Request received"+counter).getBytes());
		counter++;
		socket.setKeepAlive(true);
		Thread.sleep(1000);
		socket.close();
		return counter;
	}

}

2 thoughts on “Asynchronous Server In Java

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s