-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer.java
More file actions
100 lines (87 loc) · 2.89 KB
/
Server.java
File metadata and controls
100 lines (87 loc) · 2.89 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import java.io.*;
import java.net.*;
import java.util.*;
import java.awt.Color;
/**
* The Server class accepts and closes connections from Players
* whenever possible. It also receives and sends updates from a
* Player to all OTHER Players.
*
* @author Herman Lin
* @author Devin Zhu
*/
public class Server {
public static final int DEFAULT_PORT = 5190;
// dynamic array that allows for n players
private static ArrayList<Connection> players;
public static boolean isEmpty() { return players.isEmpty(); }
/**
* Removes a player from the list of connections
*
* @param player the player's Connection
*/
public static void removePlayer(Connection player) {
players.remove(player);
}
public static void writeToOtherPlayers(String data, Connection src) {
for (Connection p : players) {
if (p.equals(src)) { continue; }
else {
// try { p.sout.writeUTF(data); }
try { p.sout.println(data); }
catch (Exception e) {}
}
}
}
public static void main(String[] args) {
System.out.println("Booting up the server...");
players = new ArrayList<Connection>();
try {
ServerSocket ss = new ServerSocket(DEFAULT_PORT);
System.out.println("Server started with port " + DEFAULT_PORT);
while(true) {
Socket playerSocket = ss.accept();
Connection playerConn = new Connection(playerSocket);
playerConn.sout.println(players.size());
if (players.isEmpty()) playerConn.sout.println("");
playerConn.start();
players.add(playerConn);
}
} catch (Exception e) {
System.out.println("Server could not listen on port " + DEFAULT_PORT);
}
}
}
class Connection extends Thread {
Socket socket;
// DataInputStream sin;
// DataOutputStream sout;
Scanner sin;
PrintStream sout;
Connection(Socket newPlayerSocket) {
try {
// initalize the Player's socket connections
socket = newPlayerSocket;
// sin = new DataInputStream(socket.getInputStream());
// sout = new DataOutputStream(socket.getOutputStream());
sin = new Scanner(socket.getInputStream());
sout = new PrintStream(socket.getOutputStream());
} catch (IOException e) {}
}
@Override
public void run() {
try {
try {
while(true) {
String data = sin.nextLine();
Server.writeToOtherPlayers(data, this);
}
} catch (Exception e) {
} finally {
sout.println("DISCONNECT");
socket.close();
Server.removePlayer(this);
}
} catch (Exception e) {}
}
}