summaryrefslogtreecommitdiff
path: root/src/Server/ChatServer.java
blob: 641c1736f2b15d792e5b95307789b6196d6b0049 (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
package Server;
import java.net.*;
import java.io.*;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.Iterator;

public class ChatServer
{
	private ServerSocket service;
	private LinkedList<Connection> connections;
	private Hashtable <String, Boolean> nicks; 
	
	public static final int portNum = 6667;
	public static ChatServer server;
	
	/** removing connection from the iterator.
	 * @param con connection */
	public void connectionRemove(Connection con)
	{
		this.connections.remove(con);
	}
	
	/** returning ConnectionIterator. */
	public Iterator<Connection> getConnectionIterator()
	{
		return this.connections.iterator();
	}
	
	/** constructor of the server , building socket , connection list and nicks dictionary.*/
	ChatServer() throws IOException {
		this.service = new ServerSocket(portNum);
		this.connections = new LinkedList<Connection>();
		this.nicks = new Hashtable <String, Boolean>();
	}
	
	/** check if nick already used. if not add it.
	 * @param nick the new nick name to set */
	public boolean addNick (String nick)
	{
		if (this.nicks.get(nick) != null)
		{
			return false;
		}
		
		this.nicks.put(nick, true); // this value (true) has no meaning.
		return true;
	}
	
	/** remove nick which is no longer in use.
	 * @param nick the nick to remove*/
	public void removeNick (String nick)
	{
		this.nicks.remove(nick);
	}
	
	/** Listening to port and opening a socket */
	public static void main(String[] args) throws IOException
	{
		try
		{
			server = new ChatServer();
		} catch (IOException e)
		{
			System.err.println("Failed listening on port " + portNum + " (" + e + ")");
			return;
		}

		Socket soc = null;
		try
		{
			while (true)
			{
				soc = server.service.accept();
				Connection con = new Connection(soc);
				server.connections.add(con);
				con.start();
			}
		} catch (IOException e)
		{
			System.out.println(e);
		}

	}
}