-
Notifications
You must be signed in to change notification settings - Fork 0
/
Server.java
64 lines (55 loc) · 1.21 KB
/
Server.java
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
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/**
* @author martin (cernama9@fit.cvut.cz)
* @since 6.3.15.
*/
/**
* Main server class. Handles the connecting clients and starts new threads
*/
final class Server
{
private int port;
private ServerSocket socket;
public Server(int port)
{
this.port = port;
this.socket = null;
}
/**
* Starts the server. Server accepts clients in an infinite loop
*
* @throws IOException
*/
public void startServer() throws IOException
{
try
{
socket = new ServerSocket(port);
}
catch (IOException e)
{
System.err.println("Could not listen on port: " + port);
System.exit(1);
}
while (true)
{
Socket clientSocket = null;
try
{
clientSocket = socket.accept();
}
catch (IOException e)
{
System.err.println("Accept failed.");
System.exit(1);
}
System.out.println("[INFO][ ][" + clientSocket.getInetAddress() + ":" + clientSocket.getPort() + "] Client accepted");
ClientHandler runnable = new ClientHandler(clientSocket);
Thread clientThread = new Thread(runnable);
clientThread.start();
new Thread(new TheadKiller(clientThread, runnable)).start();
}
}
}