-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServerThread.java
More file actions
86 lines (79 loc) · 2.05 KB
/
Copy pathServerThread.java
File metadata and controls
86 lines (79 loc) · 2.05 KB
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
package sockets;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Класс серверного потока. Прослушка и принятие соединений происходит именно в
* нем.
*
* @author P@bloid
*/
class ServerThread extends Thread
{
/**
* Номер прослушиваемого порта
*/
private int port;
/**
* Запущен ли сервер в данный момент
*/
private boolean running;
/**
* Список подключенных клиентов
*/
private Map<Integer, ClientThread> clients = new HashMap<>();
/**
* номер первого свободного клиента
*/
private int clientId = 0;
/**
* Содать новый серверный поток
*
* @param port номер порта для прослушивания
*/
public ServerThread(int port)
{
this.port = port;
}
/**
* Главный метод потока
*/
@Override
public void run()
{
running = true;
try
{
ServerSocket ss = new ServerSocket(port);
while (running)
{
Socket s = ss.accept();
ClientThread ct = new ClientThread(s, this);
ct.setClientId(clientId);
clients.put(clientId++, ct);
ct.start();
}
ss.close();
}
catch (IOException ex)
{
Logger.getLogger(ServerThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
public synchronized void stopServer()
{
this.running = false;
}
public Map<Integer, ClientThread> getClients()
{
return clients;
}
}