-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathServer.java
More file actions
58 lines (49 loc) · 1.76 KB
/
Server.java
File metadata and controls
58 lines (49 loc) · 1.76 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
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import augie.edu.finalProgram.Belgovi.ClientHandler;
public class Server {
// Important to listen to incoming traffic
private ServerSocket serverSocket;
public Server(ServerSocket serverSocket) {
this.serverSocket = serverSocket;
}
// Start server method to keep the server running
// Accpet incoming connections
public void startServer() {
while (!serverSocket.isClosed()) {
try {
// Accept incoming traffic
Socket socket = serverSocket.accept();
// Printin the address of the client
System.out.println("New connection from " + socket.getInetAddress().getHostAddress());
// ClientHandler object to handle multiple clients which implements interface
// Runnable
ClientHandler clientHandler = new ClientHandler(socket);
// Thread object to run the clientHandler
Thread thread = new Thread(clientHandler);
thread.start();
} catch (IOException e) {
// Close the server if there is an error
System.out.println("Server closed");
closeServer();
}
}
}
// Close the server
public void closeServer() {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
{
ServerSocket serverSocket = new ServerSocket(8080);
Server server = new Server(serverSocket);
// Start the server
server.startServer();
}
}
}