-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathServer.java
111 lines (95 loc) · 2.95 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/***************************************************************
* This class contains the main function to execute the
* server side portion of the game.
**************************************************************/
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;
public class Server extends Thread
{
private final GameHandler gameHandler;
private final GameState gameState;
private ServerSocket serverSocket;
private boolean running = false;
public static ArrayList<Socket> clientSocketList = new ArrayList<Socket>();
public Server()
{
//Set up initial GameState with server start
gameState = new GameState();
gameHandler = new GameHandler(gameState);
// Set up GameHandler
startServer();
//should not be reached
stopServer();
}
public void startServer()
{
try
{
serverSocket = new ServerSocket( 55332);
this.start();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void stopServer()
{
running = false;
this.interrupt();
}
synchronized public static void removeSocket(Socket socket){
for (Iterator<Socket> socketIterator = clientSocketList.iterator(); socketIterator.hasNext();) {
Socket socketTemp = socketIterator.next();
if(socket.equals(socketTemp)) {
socketIterator.remove();
}
}
}
synchronized private void addSocket(Socket socket){
clientSocketList.add(socket);
}
public Boolean isServerConnected()
{
if(!this.serverSocket.isClosed()){
return true;
} else if(this.serverSocket.isClosed()){
return false;
} else {
System.out.println("Serious Error when testing for ServerSocket connection on IP and PORT");
return false;
}
}
@Override
public void run()
{
System.out.println( "Listening for connections" );
running = true;
while( running )
{
try
{
// Call accept() to receive the next connection
Socket socket = serverSocket.accept();
// Pass the socket to the RequestHandler thread for processing
RequestHandler requestHandler = new RequestHandler( socket, gameHandler );
//Add new socket to list of sockets
addSocket(socket);
//start the new thread
requestHandler.start();
}
catch (IOException e)
{
System.out.println("Exception in Server run()");
e.printStackTrace();
}
}
}
public static void main( String[] args )
{
Server server = new Server();
}
}