summaryrefslogtreecommitdiff
path: root/src/Server/Connection.java
blob: bcc3ac72f2d4bae53d6f6b71c8c025eafe3e575c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package Server;

import java.net.*;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

class ParsedLine
{
	private String line;
	private String command;
	private String args;
	
	public ParsedLine(String line)
	{
		this.line = line;
		String[] parsedLine = this.line.split("[ \t]+", 2);
		if (parsedLine.length > 1)
			this.args = parsedLine[1];
		else
			this.args = "";
		
		if (parsedLine.length > 0)
			this.command = parsedLine[0];
		else
			this.command = "";
	}
	
	public String getCommand()
	{
		return this.command;
	}
	
	public String getArgs()
	{
		return this.args;
	}
}

public class Connection extends Thread
{
	private Socket soc;
	private Client client;

	public Connection(Socket soc)
	{
		this.soc = soc;
	}
	
	public Client getClient()
	{
		return this.client;
	}
	
	public void shutdown() 
	{
	
		ChatServer.server.connectionRemove(this);
		ChatServer.server.removeNick(client.getNick());
		try
		{
			if (!soc.isClosed())
				soc.close();
			
		} catch (IOException e) {}
	}
	
	public String toString () 
	{
		return "[" + soc.getPort() + "]";
	}

	@SuppressWarnings("deprecation")
	public void run()
	{
		try
		{
			CommandsTable commandsTable = new CommandsTable();
			InputStreamReader InTemp = new InputStreamReader(soc.getInputStream() );
			BufferedReader input = new BufferedReader(InTemp);
			
			OutputStreamWriter outTemp = new OutputStreamWriter(soc.getOutputStream());
			BufferedWriter output = new BufferedWriter(outTemp);
			client = new Client(soc, output, this);

			while (true)
			{
				ParsedLine parsedLine;
				String line;

				try
				{
					line = input.readLine(); // FIXME: more then 1 line
				} catch (java.net.SocketException e)
				{
					break; // connection was lost / disconnected
				}
				if (line == null)
				{
					System.err.println("Got null line");
					shutdown();
					break;
				}
				parsedLine = new ParsedLine(line);
				String s = soc.getPort() + ": <" + line + ">";
				System.out.println(s);
				
				s = soc.getPort() + ": <" + line + ">, command: <" + parsedLine.getCommand() + ">, args: <" + parsedLine.getArgs() + ">.";
				commandsTable.runCommand(client, parsedLine.getCommand(), parsedLine.getArgs());
				System.out.println(s);
				// System.out.println("Done");
			}
		} catch (IOException e)
		{
			e.printStackTrace();
			shutdown();
		}
	}
}