summaryrefslogtreecommitdiff
path: root/src/Server/Connection.java
blob: d232616e8cd5463934ff2af3c56c471c658fd43b (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
package Server;

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

public class Connection extends Thread
{
	private Socket soc;
	
	public  Connection (Socket soc)
	{
		
		this.soc = soc;
	}
	

	private static String[] parseLine(String line)
	{
		String[] parsedLine = line.split("[ \t]+", 2);
		return parsedLine;
		
	}
	
	@SuppressWarnings("deprecation")
	public void run ()
	{
		try
		{
			Client client;
			CommandsTable commandsTable = new CommandsTable();
			
			DataInputStream input = new DataInputStream(soc.getInputStream());
			OutputStreamWriter outTemp = new OutputStreamWriter(soc.getOutputStream());
			BufferedWriter output = new BufferedWriter(outTemp);
			client = new Client(soc, output);
			
			while (true)
			{
				String[] 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");
					soc.close();
					break;
				}
				parsedLine = parseLine(line);
				commandsTable.runCommand(client, parsedLine[0], parsedLine[1]);
				line = soc.getPort() + ": <" + line + ">, command: <" + parsedLine[0] + ">, args: <" + parsedLine[1] + ">.";
				System.out.println(line);

				// System.out.println("Done");
			}
		} catch (IOException e)
		{
			if (soc != null)
				try {
					soc.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			e.printStackTrace();
		}
	}
}