Gå til innhold

Multi thread server - problemer med backlog


Anbefalte innlegg

Hei folkens,

 

Holder på med en øvingsoppgave som går ut på å skrive en klient som sender K antall forespørsler til en server med et mellomrom "clientWait" mellom hver forespørsel. Egen tråd pr forespørsel. Serverens "krav":

 

1. Skal bruke Threadpool, med et bestemt antall tråder, "maxNoOfThreads".

2. ServerSocket-objektet skal ha en backlog med størrelse, "backlog".

3. Forsinkelse mellom betjening av forespørslene, "serverWait".

 

Problemet: Selvom jeg setter K høy, clientWait lav, maxNoOfThreads = 1, backlog = 1 og serverWait = 1000 blir ingen av forespørslene forkastet, det tar bare laaang tid før alle forespørslene blir betjent. Hvorfor kan det være slik?

 

Håper noen kan hjelper.

 

Kode i spoiler:

 

 

 

Klient:

 

import java.net.*;
import java.io.*;


public class Client implements Runnable {


private int port = 8080;
String hostServer;

public Client(int port,String hostServer){

	this.port = port;
	this.hostServer = hostServer;

}

public static void waitManySec(long ms) {
	try {
		Thread.currentThread();
		Thread.sleep(ms);
	}
	catch (InterruptedException e) {
		e.printStackTrace();
		System.out.println("Wait has been interrupted");
		System.exit(-1);
	}
}

public void connect(String command){

	Socket connection = null;

	try {
		connection = new Socket(this.hostServer,this.port);
	} catch (UnknownHostException e) {
		System.out.println("Unknown host");
		e.printStackTrace();
	} catch (IOException e) {
		System.out.println("Error creating socket");
		e.printStackTrace();
	}


	BufferedReader inputData = null;
	DataOutputStream outputData = null;

	try {
		inputData = new BufferedReader(new InputStreamReader(connection.getInputStream()));
		outputData = new DataOutputStream(connection.getOutputStream());
	} catch (IOException e) {
		System.out.println("Error with output- or input stream");
		e.printStackTrace();
	}

	try {
		outputData.writeBytes(command);
		outputData.write(13);
		outputData.write(10);
		outputData.flush();

		int entryData;

		while((entryData = inputData.read())!=-1) {
			System.out.write(entryData);
		}

		inputData.close();

	} catch (IOException e) {
		System.out.println("Error reading socket");
		e.printStackTrace();
	}

	try {
		connection.close();
	} catch (IOException e) {
		System.out.println("Error closing socket");
		e.printStackTrace();
	}

}


public void run() {
	connect("GET /test.html");
}

public static void main(String[] args) {

	int K = 10;
	long clientWait = 1;

	for(int i = 0; i < K; i++){
		new Thread(new Client(8080,"localhost")).start();
		waitManySec(clientWait);
	}	
}

}

 

Server:

 

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

public class ThreadPooledServer implements Runnable {

final int port = 8080;
ServerSocket serverSocket;
boolean isStopped;
Thread runningThread;
int backlog;
long serverWait;
int maxNumberofThreads;

ExecutorService threadPool;

public ThreadPooledServer(int backlog, long twait, int maxNumberOfThreads){

	this.backlog = backlog;
	this.serverWait = twait;
	this.maxNumberofThreads = maxNumberOfThreads;

	threadPool = Executors.newFixedThreadPool(this.maxNumberofThreads);

}

public void run() {

	synchronized (this) {
		this.runningThread = Thread.currentThread();
	}

	openServerSocket();

	while(!isStopped()){

		Socket clientSocket = null;

		try {
			clientSocket = this.serverSocket.accept();

		} catch (IOException e) {
			e.printStackTrace();
		}

		this.threadPool.execute(new WorkerRunnable(clientSocket,this.serverWait));

	}
	this.threadPool.shutdown();
	System.out.println("Server stopped");

}

public synchronized void stop(){
	this.isStopped = true;

	try {
		this.serverSocket.close();
	} catch (IOException e) {
		e.printStackTrace();
	}

}

private synchronized boolean isStopped(){
	return this.isStopped;
}

private void openServerSocket(){
	try {
		this.serverSocket = new ServerSocket(this.port,this.backlog);
	} catch (IOException e) {
		e.printStackTrace();
	}
}

public static void main(String[] args){

	int backlog = 1;
	int maxNoOfThreads = 1;
	long serverWait = 1000;

	new Thread(new ThreadPooledServer(backlog,serverWait,maxNoOfThreads)).start();

}
}

 

WorkerRunnable (klasse for å betjene forespørsler).

 

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

public class WorkerRunnable implements Runnable {

protected Socket clientSocket;
protected String serverText;
protected long twait;

public WorkerRunnable(Socket clientSocket,long twait){
	this.clientSocket = clientSocket;
	this.twait = twait;
	System.out.println("New server thread");
}

public void run() {

	try {
		BufferedReader input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
		DataOutputStream output = new DataOutputStream(this.clientSocket.getOutputStream());

		InetAddress localMachine = InetAddress.getLocalHost();
		String clientIP = this.clientSocket.getLocalAddress().getHostAddress();
		String serverHost = localMachine.getHostName();
		String serverIP = localMachine.getHostAddress();

		SimpleDateFormat ft = new SimpleDateFormat ("hh:mm:ss");

		String inputText = input.readLine();

		if(inputText.equalsIgnoreCase("GET /TEST.html")){

			sendLine(output,"<html><head></head><body>");
			sendLine(output,"Server Hostname: "+localMachine.getHostName());
			sendLine(output,"Server IP: "+localMachine.getHostAddress());
			sendLine(output,"Client IP: "+clientIP);
			sendLine(output, "Current time: "+ft.format(new Date()));
			sendLine(output,"</body></html>");

			output.flush();

			try {
				Thread.sleep(this.twait);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

	} catch (IOException e) {
		e.printStackTrace();
	}

}

private void sendLine(DataOutputStream output, String text){

	try{
		for(int i = 0; i < text.length(); i++){

			output.write((byte)text.charAt(i));

		}

		output.write(13);
		output.write(10);
	}
	catch (IOException e) {
		e.printStackTrace();
	}
}


}

 

 

 

Lenke til kommentar
Videoannonse
Annonse

Vet ikke om jeg forstår deg helt rett, men har du lest dokumentasjonen?

 

Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue. At any point, at most nThreads threads will be active processing tasks. If additional tasks are submitted when all threads are active, they will wait in the queue until a thread is available. If any thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks. The threads in the pool will exist until it is explicitly shutdown.

 

(Egen utheving)

Lenke til kommentar

Opprett en konto eller logg inn for å kommentere

Du må være et medlem for å kunne skrive en kommentar

Opprett konto

Det er enkelt å melde seg inn for å starte en ny konto!

Start en konto

Logg inn

Har du allerede en konto? Logg inn her.

Logg inn nå
×
×
  • Opprett ny...