publicclassTicTacToeServerextendsJFrame{privatechar[]board;privateJTextAreaoutputArea;privatePlayer[]players;privateServerSocketserver;privateintcurrentPlayer;privatefina...
public class TicTacToeServer extends JFrame {
private char[] board;
private JTextArea outputArea;
private Player[] players;
private ServerSocket server;
private int currentPlayer;
private final int PLAYER_X = 0, PLAYER_O = 1;
private final char X_MARK = 'X', O_MARK = 'O';
public TicTacToeServer()
{
super( "Tic-Tac-Toe Server" );
board = new char[ 9 ];
players = new Player[ 2 ];
currentPlayer = PLAYER_X;
try {
server = new ServerSocket( 12345, 2 );
}
catch( IOException ioException ) {
ioException.printStackTrace();
System.exit( 1 );
}
outputArea = new JTextArea();
getContentPane().add( outputArea, BorderLayout.CENTER );
outputArea.setText( "Server awaiting connections\n" );
setSize( 300, 300 );
setVisible( true );
}
public void execute()
{
for ( int i = 0; i < players.length; i++ ) {
try {
players[ i ] = new Player( server.accept(), i );
players[ i ].start();
}
catch( IOException ioException ) {
ioException.printStackTrace();
System.exit( 1 );
}
}
synchronized ( players[ PLAYER_X ] ) {
players[ PLAYER_X ].setSuspended( false );
players[ PLAYER_X ].notify();
}
}
public static void main( String args[] )
{
TicTacToeServer application = new TicTacToeServer();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
application.execute();
}
private class Player extends Thread {
private Socket connection;
private DataInputStream input;
private DataOutputStream output;
private int playerNumber;
private char mark;
protected boolean suspended = true;
public Player( Socket socket, int number )
{
playerNumber = number;
mark = ( playerNumber == PLAYER_X ? X_MARK : O_MARK );
connection = socket;
try {
input = new DataInputStream( connection.getInputStream() );
output = new DataOutputStream( connection.getOutputStream() );
}
catch( IOException ioException ) {
ioException.printStackTrace();
System.exit( 1 );
}
} // end Player constructor
public void run()
{
} // end method run
} // end class Player
}
展开