Connection.java 2.67 KB
package pad.prac2;

import java.io.IOException;

public class Connection extends Thread
{
	private MySocket socket;
	private Server serv;
	private boolean sleep, kill;
	
	public Connection(Server s)
	{
		serv = s;
		kill = false;
		sleep = true;
	}
	
	public void awake()
	{
		synchronized(this)
		{
			sleep = false;
			this.notify();
		}
	}
	
	public void finish()
	{
		kill = true;
		if(sleep)
		{
			sleep = false;
			notify();
		}
		socket.close();
	}
	
	public void setSock(MySocket s)
	{
		socket = s;
	}
	
	public void sendMessage(String message) throws IOException
	{
		socket.sendMsg(message);
	}
	
	public void run()
	{
		while(!kill)
		{
			while(sleep)
			{
				try
				{
					synchronized(this)
					{
						wait();
					}
				} 
				catch (InterruptedException e)
				{
					e.printStackTrace();
				}
			}
			if(!kill)
			{
				String str;
				try
				{
					str = socket.recvMsg();
					while(str.contains(" "))
					{
						socket.sendMsg("CHATNICKINVALID");
						str = socket.recvMsg();
					}
					while(serv.isOnline(str))
					{
						socket.sendMsg("CHATNICKEXIST");
						str = socket.recvMsg();
					}
					socket.sendMsg("CHATOK");
					serv.addToChatroom(this, str);
				} 
				catch (IOException e)
				{
					if(!kill)
					{
						System.out.println("TCP: Communication with client failed while entering chatroom");
						sleep = true;
						serv.finishWorker(this);
					}
					continue;
				}
				while(true)
				{
					try
					{
						str = "/disconnect";
						str = socket.recvMsg();
						if(str.equals("/disconnect"))
						{
							socket.sendMsg("DISC_OK");
							System.out.println(serv.getNickname(this) + " disconnected");
							break;
						}
						else if(str.equals("/exit"))
						{
							socket.sendMsg("EXIT_OK");
							System.out.println(serv.getNickname(this) + " disconnected");
							break;
						}
						else if(str.equals("/who"))
						{
							socket.sendMsg(serv.listOnline());
						}
						else if(str.startsWith("@"))
						{
							try
							{
								if(!str.contains(" "))
								{
									serv.sendTo(this,str.substring(1),"");
								}
								else
								{
									serv.sendTo(this,str.substring(1,str.indexOf(' ')),str.substring(str.indexOf(' ')+1));
								}
							}
							catch(ChatException cE)
							{
								socket.sendMsg(cE.getMessage());
							}
						}
						else
						{
							System.out.println("FROM " + serv.getNickname(this) + ": " + str);
							serv.sendToChat(this,str);
						}
					}
					catch(IOException ioExc)
					{
						System.out.println("TCP: Error writing to socket");
						System.out.println(serv.getNickname(this) + " disconnected");
						break;
					}
				}
				sleep = true;
			}
			serv.finishWorker(this);
		}
	}
}