-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathServer.java
executable file
·90 lines (68 loc) · 2.17 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
package sample;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class Server{
private ServerSocket serverSocket ;
int portNumber;
private Socket playerOne;
private Socket playerTwo;
int playersReady;
public ObjectOutputStream outOne;
private ObjectOutputStream outTwo ;
public Server(){
playersReady=0;
portNumber=12345;
try{
serverSocket = new ServerSocket(portNumber);
playerOne = serverSocket.accept();
new ServerRead(playerOne,"one", this);
outOne = new ObjectOutputStream(playerOne.getOutputStream());
outOne.writeObject("1");
System.out.println("First Player Connected");
playerTwo = serverSocket.accept();
new ServerRead(playerTwo,"two", this);
outTwo = new ObjectOutputStream(playerTwo.getOutputStream());
outTwo.writeObject("2");
System.out.println("Second Player Connected");
} catch (UnknownHostException e) {
System.err.println("Host Unknown" );
}catch (IOException ioException) {
ioException.printStackTrace();
}
}
public void write(String code) throws IOException{
String player = code.substring(0,3);
if (code.substring(3).equals("ready")){
playersReady++;
if (playersReady%2==0){
startGame();
}
return;
}
if (playersReady%2!=0)return;
if (player.equals("one")){
outTwo.writeObject(code.substring(3));
}
else{
outOne.writeObject(code.substring(3));
}
}
void startGame() throws IOException{
outOne.writeObject("start");
outTwo.writeObject("start");
}
void writeGameInfo(GameInfo gameInfo) throws IOException{
if (gameInfo.from.equals("one")){
outTwo.writeObject(gameInfo);
}
else{
outOne.writeObject(gameInfo);
}
}
public static void main(String[] args){
new Server();
}
}