Blame view

JChatServer/src/pad/prac2/Connection.java 1.72 KB
1
2
package pad.prac2;
3
4
import java.io.IOException;
5
public class Connection extends Thread
6
{
7
8
9
10
11
12
13
14
15
16
17
	private MySocket socket;
	private Server serv;
	private boolean sleep, kill;

	public Connection(Server s)
	{
		serv = s;
		kill = false;
		sleep = true;
	}
18
	public void sendMessage(String message) throws IOException
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
	{
		socket.sendMsg(message);
	}

	public void awake()
	{
		synchronized(this)
		{
			sleep = false;
			this.notify();
		}
	}

	public void finish()
	{
		kill = true;
		sleep = false;
		socket.close();
		this.notify();
	}

	public void setSock(MySocket s)
	{
		socket = s;
	}

	public void run()
	{
		while(!kill)
		{
			while(sleep)
			{
				try
				{
					synchronized(this)
					{
						wait();
					}
				} 
				catch (InterruptedException e)
				{
					e.printStackTrace();
				}
			}
			String str = socket.recvMsg();
			serv.addToChatroom(this, str);
			if(!kill)
			{
				while(true)
				{
					str = socket.recvMsg();
					if(str != null)
					{
72
						try
73
						{
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
							if(str.equals("/disconnect"))
							{
								socket.sendMsg("DISC_OK");
								kill = true;
								System.out.println(serv.getNickname(this) + " disconnected");
								break;
							}
							else if(str.equals("/exit"))
							{
								socket.sendMsg("EXIT_OK");
								kill = true;
								System.out.println(serv.getNickname(this) + " disconnected");
								break;
							}
							else
							{
								System.out.println("FROM " + serv.getNickname(this) + ": " + str);
								serv.sendToChat(this,str);
							}
93
						}
94
						catch(IOException ioExc)
95
						{
96
97
							System.out.println("TCP: Error writing to socket");
							break;
98
99
100
101
102
103
104
105
106
107
108
109
						}
					}
					else
					{
						break;
					}
				}
				sleep = true;
			}
			serv.finishWorker(this);
		}
	}
110
111

}