📄 fbfwatcher.java
字号:
// FBFWatcher.java
// Andrew Davison, June 2003, dandrew@ratree.psu.ac.th
/* FBFWatcher monitors the stream coming from the server
which will contain messages that must be processed by
the client (a NetFourByFour object)
Incoming Messages:
ok <playerID> -- connection accepted; include player ID
full -- connection refused; server has enough players
tooFewPlayers -- turn rejected, since not enough players
otherTurn <player> <posn> -- turn by other player sent to client
added <player> -- other player added to server
removed <player> -- other player removed
*/
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
public class FBFWatcher extends Thread
{
private NetFourByFour fbf; // ref back to client
private BufferedReader in;
public FBFWatcher(NetFourByFour fbf, BufferedReader i)
{ this.fbf = fbf;
in = i;
}
public void run()
// Read server messages and act on them
{
String line;
try {
while ((line = in.readLine()) != null) {
if (line.startsWith("ok"))
extractID(line.substring(3));
else if (line.startsWith("full"))
fbf.disable("full game"); // disable client
else if (line.startsWith("tooFewPlayers"))
fbf.disable("other player has left"); // disable client
else if (line.startsWith("otherTurn"))
extractOther(line.substring(10));
else if (line.startsWith("added")) // don't use ID
fbf.addPlayer(); // client adds other player
else if (line.startsWith("removed")) // don't use ID
fbf.removePlayer(); // client removes other player
else // anything else
System.out.println("ERR: " + line + "\n");
}
}
catch(Exception e) // socket closure will cause termination of while
{ // System.out.println("Socket closed");
fbf.disable("server link lost"); // end game as well
}
} // end of run()
private void extractID(String line)
// line format: <player id>
{
StringTokenizer tokens = new StringTokenizer(line);
try {
int id = Integer.parseInt( tokens.nextToken() );
fbf.setPlayerID(id); // client gets its playerID
}
catch(NumberFormatException e)
{ System.out.println(e); }
} // end of extractID()
private void extractOther(String line)
// line format: <player id> <posn>
{
StringTokenizer tokens = new StringTokenizer(line);
try {
int playerID = Integer.parseInt( tokens.nextToken() );
int posn = Integer.parseInt( tokens.nextToken() );
fbf.doMove(posn, playerID); // client executes the other player's move
}
catch(NumberFormatException e)
{ System.out.println(e); }
} // end of extractOther()
} // end of FBFWatcher
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -