-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathServer.java
More file actions
61 lines (48 loc) · 1.79 KB
/
Copy pathServer.java
File metadata and controls
61 lines (48 loc) · 1.79 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
package main.back.controller;
import main.back.account.Player;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
public class Server extends WebSocketServer {
private static final int PORT = 4444;
private Set<WebSocket> conns;
public Server() {
super(new InetSocketAddress(PORT));
conns = new HashSet<>();
}
public void onStart() {
}
public void onOpen(WebSocket conn, ClientHandshake handshake) {
conns.add(conn);
System.out.println("New connection from " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
}
public void onClose(WebSocket conn, int code, String reason, boolean remote) {
conns.remove(conn);
System.out.println("Closed connection to " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
}
public void onMessage(WebSocket conn, String message) {
System.out.println(message);
conn.send(resolve(message.trim().split(" ")));
}
public void onError(WebSocket conn, Exception e) {
if (conn != null) {
conns.remove(conn);
}
System.out.println("ERROR from " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
}
private String resolve(String[] tokens) {
switch (tokens[0]) {
case "user":
return UserCommand.resolve(Arrays.copyOfRange(tokens, 1, tokens.length));
case "game":
return GameCommand.resolve(Arrays.copyOfRange(tokens, 1, tokens.length));
default:
return "failed command";
}
}
}