Worker.java 1.52 KB
package pad.prac2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

public class Worker extends Thread
{
	private PrintWriter output;
	private BufferedReader input;
	private MySocket sock;
	private boolean run;
	private boolean kill;
	private boolean sleep;
	private Server serv;
	
	public Worker(Server srv, MySocket s, BufferedReader i, PrintWriter o)
	{
		sock = s;
		output = o;
		input = i;
		run = false;
		kill = false;
		sleep = true;
		serv = srv;
	}
	
	public void finish()
	{
		kill = true;
		run = false;
		sleep = false;
		sock.close();
	}
	
	public void run()
	{
		while(!kill)
		{
			while(sleep)
			{
				try
				{
					wait();
				} 
				catch (InterruptedException e)
				{
					e.printStackTrace();
				}
			}
			while(run)
			{
				if(output == null && input != null)
				{
					String str, length;
					while(true)
					{
						try
						{
							str = input.readLine();
							length = new Integer(str.length()).toString();
							sock.write(length, length.length());
							sock.write(str, str.length());
						}
						catch(IOException ioExc)
						{
							run = false;
							sleep = true;
							break;
						}
					}
				}
				else if(input == null && output != null)
				{
					String len, str;
					while((len = sock.readLine()) != null)
					{
						int length = Integer.parseInt(len);
						str = sock.read(length);
						output.println(str);
					}
					run = false;
					sleep = true;
				}
			}
		}
	}
	
	public void awake()
	{
		run = true;
		sleep = false;
		this.notify();
	}
}