NETWORK IMPORT
Is it possible to network import full database using impdp?
Thanks for your help.
Hi, thats is not posible the <b>impdp</b> work only in server enviroment or server architecture, you can use the <b>imp</b> for network import.
<br>
Luck.
<br>
<br>
Have a good day.
<br>
<br>
Regards
<br>
Similar Messages
-
Datapump network import from 10g to 11g database is not progressing
We have an 11.2.0.3 shell database in RedHat Linux 5 64-bit platform, and we are pulling data from its 10g database (10.2.0.4) HP-UX platform using datapump via NETWORK_LINK. However, the import seems to be not progressing and completing. We have left it run for almost 13 hours and did not even import a single row to the 11g database. We even try to import only one table with 0 rows but still it is not completing, the logfile just continue to be lopping on the following:
Worker 1 Status:
Process Name: DW00
State: EXECUTING
Estimate in progress using BLOCKS method...
Job: IMP_NONLONG4_5
Operation: IMPORT
Mode: TABLE
State: EXECUTING
Bytes Processed: 0
Current Parallelism: 1
Job Error Count: 0
Worker 1 Status:
Process Name: DW00
State: EXECUTING
We also see this:
EVENT SECONDS_IN_WAIT STATUS STATE ACTION
SQL*Net message from dblink 4408 ACTIVE WAITING IMP_NONLONG4_5
Below is our par file:
NETWORK_LINK=DATABASE_10G
DIRECTORY=MOS_UPGRADE_DUMPLOC1
LOGFILE=imp_nonlong_grp-4_5.log
STATUS=300
CONTENT=DATA_ONLY
JOB_NAME=IMP_NONLONG4_5
TABLES=SYSADM.TEST_TBL
Any ideas? Thanks.Thanks a lot for all who have looked and responded to this, I appreciate you giving time for suggestions. As a recap, datapump export and import via dumpfile works on both 10g and 11g databases, we are only having issue pulling data from the 10g database by executing datapump network import (using dblink) from the 11g database.
SOLUTION: The culprit was the parameter optimizer_features_enable='8.1.7' that is currently set on the 10g database, we have taken that out of the parameter file of the 10g database and network import worked flawlessly.
HOW DID WE FIGURE OUT: We turned on a trace to the datapump sessions and trace file shows something about optimizer (see below). So we have taken one by one any parameter that has something to do with optimizer and found out it was optimizer_features_enable='8.1.7' parameter that when removed makes the network import successful.
SELECT /* OPT_DYN_SAMP */ /*+ ALL_ROWS opt_param('parallel_execution_enabled',
'false') NO_PARALLEL(SAMPLESUB) NO_PARALLEL_INDEX(SAMPLESUB) NO_SQL_TUNE
*/ NVL(SUM(C1),0), NVL(SUM(C2),0), NVL(SUM(C3),0)
FROM
(SELECT /*+ NO_PARALLEL("SYS_IMPORT_TABLE_02") INDEX("SYS_IMPORT_TABLE_02"
SYS_C00638241) NO_PARALLEL_INDEX("SYS_IMPORT_TABLE_02") */ 1 AS C1, 1 AS C2,
1 AS C3 FROM "DBSCHEDUSER"."SYS_IMPORT_TABLE_02" "SYS_IMPORT_TABLE_02"
WHERE "SYS_IMPORT_TABLE_02"."PROCESS_ORDER"=:B1 AND ROWNUM <= 2500)
SAMPLESUB
SELECT /* OPT_DYN_SAMP */ /*+ ALL_ROWS IGNORE_WHERE_CLAUSE
NO_PARALLEL(SAMPLESUB) opt_param('parallel_execution_enabled', 'false')
NO_PARALLEL_INDEX(SAMPLESUB) NO_SQL_TUNE */ NVL(SUM(C1),0), NVL(SUM(C2),0)
FROM
(SELECT /*+ IGNORE_WHERE_CLAUSE NO_PARALLEL("SYS_IMPORT_TABLE_02")
FULL("SYS_IMPORT_TABLE_02") NO_PARALLEL_INDEX("SYS_IMPORT_TABLE_02") */ 1
AS C1, CASE WHEN "SYS_IMPORT_TABLE_02"."PROCESS_ORDER"=:B1 THEN 1 ELSE 0
END AS C2 FROM "DBSCHEDUSER"."SYS_IMPORT_TABLE_02" "SYS_IMPORT_TABLE_02")
SAMPLESUB -
Datapump Network Import from Oracle 10.2.0 to 10.1.0
I have self-developed table bulk copy system based on dmbs_datapump API. It is pretty stable and worked very well for a long time on many servers with oracle 10.1.0. But some days ago we have installed new oracle server with oracle 10.2.0 and have noticed, that our system can't copy tables from new server to another servers. After some time of debugging we got description for our situation... dbms_datapump.open() call is failing with "ORA-39006: internal error" exception. dmbs_dapatump.get_status() returns more detailed description: "ORA-39022: Database version 10.2.0.1.0 is not supported."... We're really disappointed... what we can do to use dbms_datapump.open on 10.1.0 to copy table from 10.2.0?
P.S. We have tried to use different values (COMPATIBLE, LATEST, 10.0.0, 10.1.0) for version parameter of open()... but without luck...
Please, help, because we can't upgrade such many old servers to 10.2.0 and we really need to use this new server...
Thanks in advance,
Alexey KovyrinHello,
Your problem is about the Character Set.
WE8ISO8859P1 stores character in *1* byte but AL32UTF8 (Unicode) uses up to *4* bytes.
So, when you Import from WE8ISO8859P1 to AL32UTF8 you may have the offending error ORA-12899.
To solve it, you may change the option of the Datatype of your column. And choose the option CHAR
instead of BYTE (the default), for instance:
VARCHAR2 (100) --> VARCHAR2(100 CHAR)Then, you could import the data.
You may also change the parameter NLS_LENGTH_SEMANTICS to CHAR.
alter system set nls_length_semantics=char scope=spfile;Then, restart your database.
NB: Although the parameter nls_length_semantics is dynamic you have to restart the database so
that it's taken into account.
Then, you create the Tables (empty) and afterwards you run your Import.
Hope this help.
Best regards,
Jean-Valentin
Edited by: Lubiez Jean-Valentin on Mar 21, 2010 4:26 PM -
Windows 8.1: Unable to connect to IBSS network with a profile installed manually
I created an IBSS network, Imported the IBSS profile and trying to connect from my Windows 8.1 machine. It was not connecting to the network for some reason. Is it supported in Windows 8.1?
I was able to connect to the network from Windows 7 machine using same IBSS profile, But not with Windows 8.1. Is there any known issue related to this?Hi,
Please take a look at the following articles regarding IBSS network:
Connection Operation Guidelines for Independent BSS Networks
Please note: IBSS (Ad hoc) and SoftAP are deprecated. Starting with Windows 8.1 and Windows Server 2012 R2, use Wi-Fi Direct.
Wi-Fi Direct Miniport Initialization and Configuration
Best regards
Michael Shao
TechNet Community Support -
Export and Import data or Matadata only
Aloha,
I need to update an instance, update data only with a full dump. What parameter should i use on import. How can i drop the schema without touching the metadata and database objects?
Thanks in advance.
HadesTheHades0210 wrote:
Hi,
Yes, i will import a full dump export but data only that i need to import and existing db_objects and metadata on the instance should not be touch.
Regards,
Hadeseasy as pie
[oracle@localhost ~]$ impdp help=yes
Import: Release 11.2.0.2.0 - Production on Mon Feb 4 19:57:10 2013
Copyright (c) 1982, 2009, Oracle and/or its affiliates. All rights reserved.
The Data Pump Import utility provides a mechanism for transferring data objects
between Oracle databases. The utility is invoked with the following command:
Example: impdp scott/tiger DIRECTORY=dmpdir DUMPFILE=scott.dmp
You can control how Import runs by entering the 'impdp' command followed
by various parameters. To specify parameters, you use keywords:
Format: impdp KEYWORD=value or KEYWORD=(value1,value2,...,valueN)
Example: impdp scott/tiger DIRECTORY=dmpdir DUMPFILE=scott.dmp
USERID must be the first parameter on the command line.
The available keywords and their descriptions follow. Default values are listed within square brackets.
ATTACH
Attach to an existing job.
For example, ATTACH=job_name.
CLUSTER
Utilize cluster resources and distribute workers across the Oracle RAC.
Valid keyword values are: [Y] and N.
CONTENT
Specifies data to load.
Valid keywords are: [ALL], DATA_ONLY and METADATA_ONLY.
DATA_OPTIONS
Data layer option flags.
Valid keywords are: SKIP_CONSTRAINT_ERRORS.
DIRECTORY
Directory object to be used for dump, log and SQL files.
DUMPFILE
List of dump files to import from [expdat.dmp].
For example, DUMPFILE=scott1.dmp, scott2.dmp, dmpdir:scott3.dmp.
ENCRYPTION_PASSWORD
Password key for accessing encrypted data within a dump file.
Not valid for network import jobs.
ESTIMATE
Calculate job estimates.
Valid keywords are: [BLOCKS] and STATISTICS.
EXCLUDE
Exclude specific object types.
For example, EXCLUDE=SCHEMA:"='HR'".
FLASHBACK_SCN
SCN used to reset session snapshot.
FLASHBACK_TIME
Time used to find the closest corresponding SCN value.
FULL
Import everything from source [Y].
HELP
Display help messages [N].
INCLUDE
Include specific object types.
For example, INCLUDE=TABLE_DATA.
JOB_NAME
Name of import job to create.
LOGFILE
Log file name [import.log].
NETWORK_LINK
Name of remote database link to the source system.
NOLOGFILE
Do not write log file [N].
PARALLEL
Change the number of active workers for current job.
PARFILE
Specify parameter file.
PARTITION_OPTIONS
Specify how partitions should be transformed.
Valid keywords are: DEPARTITION, MERGE and [NONE].
QUERY
Predicate clause used to import a subset of a table.
For example, QUERY=employees:"WHERE department_id > 10".
REMAP_DATA
Specify a data conversion function.
For example, REMAP_DATA=EMP.EMPNO:REMAPPKG.EMPNO.
REMAP_DATAFILE
Redefine data file references in all DDL statements.
REMAP_SCHEMA
Objects from one schema are loaded into another schema.
REMAP_TABLE
Table names are remapped to another table.
For example, REMAP_TABLE=HR.EMPLOYEES:EMPS.
REMAP_TABLESPACE
Tablespace objects are remapped to another tablespace.
REUSE_DATAFILES
Tablespace will be initialized if it already exists [N].
SCHEMAS
List of schemas to import.
SERVICE_NAME
Name of an active Service and associated resource group to constrain Oracle RAC resources.
SKIP_UNUSABLE_INDEXES
Skip indexes that were set to the Index Unusable state.
SOURCE_EDITION
Edition to be used for extracting metadata.
SQLFILE
Write all the SQL DDL to a specified file.
STATUS
Frequency (secs) job status is to be monitored where
the default [0] will show new status when available.
STREAMS_CONFIGURATION
Enable the loading of Streams metadata
TABLE_EXISTS_ACTION
Action to take if imported object already exists.
Valid keywords are: APPEND, REPLACE, [SKIP] and TRUNCATE.
TABLES
Identifies a list of tables to import.
For example, TABLES=HR.EMPLOYEES,SH.SALES:SALES_1995.
TABLESPACES
Identifies a list of tablespaces to import.
TARGET_EDITION
Edition to be used for loading metadata.
TRANSFORM
Metadata transform to apply to applicable objects.
Valid keywords are: OID, PCTSPACE, SEGMENT_ATTRIBUTES and STORAGE.
TRANSPORTABLE
Options for choosing transportable data movement.
Valid keywords are: ALWAYS and [NEVER].
Only valid in NETWORK_LINK mode import operations.
TRANSPORT_DATAFILES
List of data files to be imported by transportable mode.
TRANSPORT_FULL_CHECK
Verify storage segments of all tables [N].
TRANSPORT_TABLESPACES
List of tablespaces from which metadata will be loaded.
Only valid in NETWORK_LINK mode import operations.
VERSION
Version of objects to import.
Valid keywords are: [COMPATIBLE], LATEST or any valid database version.
Only valid for NETWORK_LINK and SQLFILE.
The following commands are valid while in interactive mode.
Note: abbreviations are allowed.
CONTINUE_CLIENT
Return to logging mode. Job will be restarted if idle.
EXIT_CLIENT
Quit client session and leave job running.
HELP
Summarize interactive commands.
KILL_JOB
Detach and delete job.
PARALLEL
Change the number of active workers for current job.
START_JOB
Start or resume current job.
Valid keywords are: SKIP_CURRENT.
STATUS
Frequency (secs) job status is to be monitored where
the default [0] will show new status when available.
STOP_JOB
Orderly shutdown of job execution and exits the client.
Valid keywords are: IMMEDIATE. -
EBS 11.5.10cu2 database upgrade using network dpimp
Hi,
I am upgradeing all my Oracle db's to 11.2.0.2
I have done the upgrade successfully for our custom student system, bpel and OEM.
The plan I followed for this environments was:
install Oracle db 11.2 on the new server (upgrading the hardware and OS at the same time to)
create the db
import datapump via network link the data
del stats ,gather stats and
point the apps to the new db.
But now I am a little stuck with db EBS db . It is about 250 gig's in size, so to do test runs on the above proses takes time.
The source db is 10.2.4 running on a single instance in ASM. RHEL 5.7
The target db is 11.2.0.2 running on a single instance with grid infrastructure for standalone server, in ASM on a vmware virtual server. RHEL 5.8
The EBS consists mainly of the HR and fin modules.
I used Note 881505.1
Interoperability Notes
Oracle E-Business Suite Release 11i
with Oracle Database 11g Release 2 (11.2.0)
and Export/import notes on Applications 11i Database 11g [ID 557738.1]
To create the db , and then import everything
But after the import I saw there are lots of EBS objects in the system schema of the source database that was not in my target db.
How do I create these objects. It include things like views, queue tables and custom data types.
I do not want to do the imort into a 10g db and then upgrade to 11g. I want a nice clean db after the upgrade.
thank you
Phillip du PlooyHallo Hussein,
Thanks for the reply . I saw in the following export/import parameter file ($AU_TOP/patch/115/import/auexpdp.dat ) that the sys and system schema's are also imported into the new db.
Is this not a probleme? Because I am importing into a 11g db from 10g. Will the "old" sys/system objects that is brought over not create problems for my 11g db?
I have done a network import like I described above (excluding sys en system, and afterwards recreated all the missing objects) but the EBS work flow is not working 100%
So I think if I include sys and system this will also work, but what about the 10g sys objects in my 11g db? Is there not a better way to recreate all these objects?
Thank you
Phillip du Plooy -
Quick easy question on network programming
I'm just starting java programming having done quite a bit of C++ but im struggling to get anywhere. Im trying to get 2 computers on my network to communicate and compiling my program is fine, but when i execute it i get a bunch of errors that i dont understand.
My code for the sender is below can anyone spot any obvious mistakes?
The errors i get are:
java.lang.NoClassDefFoundError: pkg/ex10sender (wrong name: ex10sender)
at java.lang.ClassLoader.defineClass0(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:537)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:123)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:251)
at java.net.URLClassLoader.access$100(URLClassLoader.java:55)
at java.net.URLClassLoader$1.run(URLClassLoader.java:194)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:187)
at java.lang.ClassLoader.loadClass(ClassLoader.java:289)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:274)
at java.lang.ClassLoader.loadClass(ClassLoader.java:235)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:302)
Exception in thread "main"
import java.net.*; // for network
import java.util.*; // for utilities
import java.io.*; // for streams
public class ex10sender
public static void main(String[] argv)
try
InetAddress addr = InetAddress.getLocalHost();
int sendPortNumber = 4000;
int portNumber = 3000;
String bob = "hello";
byte[] buffer = bob.getBytes();
// assume that machine and port to send to are in arg vector
if (argv.length == 3)
try
addr = InetAddress.getByName(argv[0]);//comp name
portNumber = Integer.parseInt(argv[1]);//portNum
bob = argv[2]; //string to send
buffer = bob.getBytes();
catch (UnknownHostException uh)
addr = InetAddress.getLocalHost();
int size = 0;
// now create and send packet
DatagramPacket packet =
new DatagramPacket(buffer,buffer.length,addr,portNumber);
DatagramSocket socket = new DatagramSocket(sendPortNumber);
System.out.println("ready to send on " + portNumber+
" port: " + socket.getLocalPort());
socket.send(packet);
System.out.println("Packet data sent");
catch (UnknownHostException uh)
System.out.println("ERROR: " + uh);
System.exit(0);
catch (IOException ioe)
System.out.println("ERROR: " + ioe);
}Impressive! 3 replies in about 30 seconds!
Thanks for all your help, yes the problem was that i was running the program inside a package. Stuck "package pkg" at the top and all is well.
Thanks so much, now at least i can begin testing my code to see if it works :)
Lewis -
Hi
I used Deitel's code of TicTacToe program that creats a server and have 2 clients playing TicTacToe. When the game is over one of the client has to click on new game and a new game will begin. I don't know how to do this.
Please Help.
Here's the code for the server
import java.awt.BorderLayout;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
import java.util.Formatter;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.Condition;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class TicTacToeServer extends JFrame
private String[] board = new String[ 9 ]; // tic-tac-toe board
private JTextArea outputArea; // for outputting moves
private Player[] players; // array of Players
private ServerSocket server; // server socket to connect with clients
private int currentPlayer; // keeps track of player with current move
private final static int PLAYER_X = 0; // constant for first player
private final static int PLAYER_O = 1; // constant for second player
private final static String[] MARKS = { "X", "O" }; // array of marks
private ExecutorService runGame; // will run players
private Lock gameLock; // to lock game for synchronization
private Condition otherPlayerConnected; // to wait for other player
private Condition otherPlayerTurn; // to wait for other player's turn
// set up tic-tac-toe server and GUI that displays messages
public TicTacToeServer()
super( "Tic-Tac-Toe Server" ); // set title of window
// create ExecutorService with a thread for each player
runGame = Executors.newFixedThreadPool( 2 );
gameLock = new ReentrantLock(); // create lock for game
// condition variable for both players being connected
otherPlayerConnected = gameLock.newCondition();
// condition variable for the other player's turn
otherPlayerTurn = gameLock.newCondition();
for ( int i = 0; i < 9; i++ )
board[ i ] = new String( "" ); // create tic-tac-toe board
players = new Player[ 2 ]; // create array of players
currentPlayer = PLAYER_X; // set current player to first player
try
server = new ServerSocket( 12345, 2 ); // set up ServerSocket
} // end try
catch ( IOException ioException )
ioException.printStackTrace();
System.exit( 1 );
} // end catch
outputArea = new JTextArea(); // create JTextArea for output
add( outputArea, BorderLayout.CENTER );
outputArea.setText( "Server awaiting connections\n" );
setSize( 300, 300 ); // set size of window
setVisible( true ); // show window
} // end TicTacToeServer constructor
// wait for two connections so game can be played
public void execute()
// wait for each client to connect
for ( int i = 0; i < players.length; i++ )
try // wait for connection, create Player, start runnable
players[ i ] = new Player( server.accept(), i );
runGame.execute( players[ i ] ); // execute player runnable
} // end try
catch ( IOException ioException )
ioException.printStackTrace();
System.exit( 1 );
} // end catch
} // end for
gameLock.lock(); // lock game to signal player X's thread
try
players[ PLAYER_X ].setSuspended( false ); // resume player X
otherPlayerConnected.signal(); // wake up player X's thread
} // end try
finally
gameLock.unlock(); // unlock game after signalling player X
} // end finally
} // end method execute
// display message in outputArea
private void displayMessage( final String messageToDisplay )
// display message from event-dispatch thread of execution
SwingUtilities.invokeLater(
new Runnable()
public void run() // updates outputArea
outputArea.append( messageToDisplay ); // add message
} // end method run
} // end inner class
); // end call to SwingUtilities.invokeLater
} // end method displayMessage
// determine if move is valid
public boolean validateAndMove( int location, int player )
// while not current player, must wait for turn
while ( player != currentPlayer )
gameLock.lock(); // lock game to wait for other player to go
try
otherPlayerTurn.await(); // wait for player's turn
} // end try
catch ( InterruptedException exception )
exception.printStackTrace();
} // end catch
finally
gameLock.unlock(); // unlock game after waiting
} // end finally
} // end while
// if location not occupied, make move
if ( !isOccupied( location ) )
board[ location ] = MARKS[ currentPlayer ]; // set move on board
currentPlayer = ( currentPlayer + 1 ) % 2; // change player
// let new current player know that move occurred
players[ currentPlayer ].otherPlayerMoved( location );
gameLock.lock(); // lock game to signal other player to go
try
otherPlayerTurn.signal(); // signal other player to continue
} // end try
finally
gameLock.unlock(); // unlock game after signaling
} // end finally
return true; // notify player that move was valid
} // end if
else // move was not valid
return false; // notify player that move was invalid
} // end method validateAndMove
// determine whether location is occupied
public boolean isOccupied( int location )
if ( board[ location ].equals( MARKS[ PLAYER_X ] ) ||
board [ location ].equals( MARKS[ PLAYER_O ] ) )
return true; // location is occupied
else
return false; // location is not occupied
} // end method isOccupied
// place code in this method to determine whether game over
public boolean isGameOver()
if( ( !board[ 0 ].equals( "" ) &&
!board[ 1 ].equals( "" ) &&
!board[ 2 ].equals( "" ) &&
!board[ 3 ].equals( "" ) &&
!board[ 4 ].equals( "" ) &&
!board[ 5 ].equals( "" ) &&
!board[ 6 ].equals( "" ) &&
!board[ 7 ].equals( "" ) &&
!board[ 8 ].equals( "" ) ) )
players[0].gameOver("Game Over, no winner");
players[1].gameOver("Game Over, no winner");
return true;
else if( board[ 0 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 1 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 2 ].equals( MARKS[ PLAYER_X ] ) )
players[0].gameOver("Player X wins");
players[1].gameOver("Player X wins");
return true;
else if( board [ 0 ].equals( MARKS[ PLAYER_O ]) &&
board [ 1 ].equals( MARKS[ PLAYER_O ]) &&
board [ 2 ].equals( MARKS[ PLAYER_O ]) )
players[0].gameOver("Player O wins");
players[1].gameOver("Player O wins");
return true;
else if( board[ 3 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 4 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 5 ].equals( MARKS[ PLAYER_X ] ) )
players[0].gameOver("Player X wins");
players[1].gameOver("Player X wins");
return true;
else if( board [ 3 ].equals( MARKS[ PLAYER_O ]) &&
board [ 4 ].equals( MARKS[ PLAYER_O ]) &&
board [ 5 ].equals( MARKS[ PLAYER_O ]) )
players[0].gameOver("Player O wins");
players[1].gameOver("Player O wins");
return true;
else if( board[ 6 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 7 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 8 ].equals( MARKS[ PLAYER_X ] ) )
players[0].gameOver("Player X wins");
players[1].gameOver("Player X wins");
return true;
else if( board [ 6 ].equals( MARKS[ PLAYER_O ]) &&
board [ 7 ].equals( MARKS[ PLAYER_O ]) &&
board [ 8 ].equals( MARKS[ PLAYER_O ]) )
players[0].gameOver("Player O wins");
players[1].gameOver("Player O wins");
return true;
else if( board[ 0 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 3 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 6 ].equals( MARKS[ PLAYER_X ] ) )
players[0].gameOver("Player X wins");
players[1].gameOver("Player X wins");
return true;
else if( board[ 0 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 3 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 6 ].equals( MARKS[ PLAYER_X ] ) )
players[0].gameOver("Player O wins");
players[1].gameOver("Player O wins");
return true;
else if( board[ 1 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 4 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 7 ].equals( MARKS[ PLAYER_X ] ) )
players[0].gameOver("Player X wins");
players[1].gameOver("Player X wins");
return true;
else if( board [ 1 ].equals( MARKS[ PLAYER_O ]) &&
board [ 4 ].equals( MARKS[ PLAYER_O ]) &&
board [ 7 ].equals( MARKS[ PLAYER_O ]) )
players[0].gameOver("Player O wins");
players[1].gameOver("Player O wins");
return true;
else if( board[ 2 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 5 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 8 ].equals( MARKS[ PLAYER_X ] ) )
players[0].gameOver("Player X wins");
players[1].gameOver("Player X wins");
return true;
else if( board [ 2 ].equals( MARKS[ PLAYER_O ]) &&
board [ 5 ].equals( MARKS[ PLAYER_O ]) &&
board [ 8 ].equals( MARKS[ PLAYER_O ]) )
players[0].gameOver("Player O wins");
players[1].gameOver("Player O wins");
return true;
else if( board[ 0 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 4 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 8 ].equals( MARKS[ PLAYER_X ] ) )
players[0].gameOver("Player X wins");
players[1].gameOver("Player X wins");
return true;
else if( board [ 0 ].equals( MARKS[ PLAYER_O ]) &&
board [ 4 ].equals( MARKS[ PLAYER_O ]) &&
board [ 8 ].equals( MARKS[ PLAYER_O ]) )
players[0].gameOver("Player O wins");
players[1].gameOver("Player O wins");
return true;
else if( board[ 2 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 4 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 8 ].equals( MARKS[ PLAYER_X ] ) )
players[0].gameOver("Player X wins");
players[1].gameOver("Player X wins");
return true;
else if( board [ 2 ].equals( MARKS[ PLAYER_O ]) &&
board [ 4 ].equals( MARKS[ PLAYER_O ]) &&
board [ 8 ].equals( MARKS[ PLAYER_O ]) )
players[0].gameOver("Player O wins");
players[1].gameOver("Player O wins");
return true;
else
return false; // this is left as an exercise
} // end method isGameOver
// private inner class Player manages each Player as a runnable
private class Player implements Runnable
private Socket connection; // connection to client
private Scanner input; // input from client
private Formatter output; // output to client
private int playerNumber; // tracks which player this is
private String mark; // mark for this player
private boolean suspended = true; // whether thread is suspended
// set up Player thread
public Player( Socket socket, int number )
playerNumber = number; // store this player's number
mark = MARKS[ playerNumber ]; // specify player's mark
connection = socket; // store socket for client
try // obtain streams from Socket
input = new Scanner( connection.getInputStream() );
output = new Formatter( connection.getOutputStream() );
} // end try
catch ( IOException ioException )
ioException.printStackTrace();
System.exit( 1 );
} // end catch
} // end Player constructor
// send message that other player moved
public void otherPlayerMoved( int location )
output.format( "Opponent moved\n" );
output.format( "%d\n", location ); // send location of move
output.flush(); // flush output
} // end method otherPlayerMoved
// control thread's execution
public void run()
// send client its mark (X or O), process messages from client
try
displayMessage( "Player " + mark + " connected\n" );
output.format( "%s\n", mark ); // send player's mark
output.flush(); // flush output
// if player X, wait for another player to arrive
if ( playerNumber == PLAYER_X )
output.format( "%s\n%s", "Player X connected",
"Waiting for another player\n" );
output.flush(); // flush output
gameLock.lock(); // lock game to wait for second player
try
while( suspended )
otherPlayerConnected.await(); // wait for player O
} // end while
} // end try
catch ( InterruptedException exception )
exception.printStackTrace();
} // end catch
finally
gameLock.unlock(); // unlock game after second player
} // end finally
// send message that other player connected
output.format( "Other player connected. Your move.\n" );
output.flush(); // flush output
} // end if
else
output.format( "Player O connected, please wait\n" );
output.flush(); // flush output
} // end else
// while game not over
while ( !isGameOver() )
int location = 0; // initialize move location
if ( input.hasNext() )
location = input.nextInt(); // get move location
// check for valid move
if ( validateAndMove( location, playerNumber ) )
displayMessage( "\nlocation: " + location );
output.format( "Valid move.\n" ); // notify client
output.flush(); // flush output
} // end if
else // move was invalid
output.format( "Invalid move, try again\n" );
output.flush(); // flush output
} // end else
} // end while
} // end try
finally
try
connection.close(); // close connection to client
} // end try
catch ( IOException ioException )
ioException.printStackTrace();
System.exit( 1 );
} // end catch
} // end finally
} // end method run
// set whether or not thread is suspended
public void setSuspended( boolean status )
suspended = status; // set value of suspended
} // end method setSuspended
public void gameOver(String msg)
if(msg.equals("Game Over, no winner"))
if ( playerNumber == PLAYER_X )
output.format( "no winner, you loose\n" );
output.flush(); // flush output
} // end if
else
output.format( "no winner, you loose\n" );
output.flush(); // flush output
} // end else
gameLock.lock();
else if(msg.equals("Player X wins"))
if ( playerNumber == PLAYER_X )
output.format(msg + "\n" );
output.flush(); // flush output
} // end if
else
output.format(msg + ", you loose\n" );
output.flush(); // flush output
} // end else
gameLock.lock();
else if(msg.equals("Player O wins"))
if ( playerNumber == PLAYER_X )
//players[1].
output.format(msg + ", you loose\n" );
output.flush(); // flush output
} // end if
else
output.format(msg + "\n" );
output.flush(); // flush output
} // end else
gameLock.lock();
else
} // end class Player
} // end class TicTacToeServer
*****and here's the code for the client
// Fig. 24.15: TicTacToeClient.java
// Client that let a user play Tic-Tac-Toe with another across a network.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.*;
import java.net.Socket;
import java.net.InetAddress;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
import java.util.Formatter;
import java.util.Scanner;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
public class TicTacToeClient extends JFrame implements Runnable
private JTextField idField; // textfield to display player's mark
private JTextArea displayArea; // JTextArea to display output
private JPanel boardPanel; // panel for tic-tac-toe board
private JPanel panel2; // panel to hold board
private JButton btnNew;
private Square board[][]; // tic-tac-toe board
private Square currentSquare; // current square
private Socket connection; // connection to server
private Scanner input; // input from server
private Formatter output; // output to server
private String ticTacToeHost; // host name for server
private String myMark; // this client's mark
private boolean myTurn; // determines which client's turn it is
private final String X_MARK = "X"; // mark for first client
private final String O_MARK = "O"; // mark for second client
// set up user-interface and board
public TicTacToeClient( String host )
ticTacToeHost = host; // set name of server
displayArea = new JTextArea( 4, 30 ); // set up JTextArea
displayArea.setEditable( false );
add( new JScrollPane( displayArea ), BorderLayout.SOUTH );
boardPanel = new JPanel(); // set up panel for squares in board
boardPanel.setLayout( new GridLayout( 3, 3, 0, 0 ) );
board = new Square[ 3 ][ 3 ]; // create board
// loop over the rows in the board
for ( int row = 0; row < board.length; row++ )
// loop over the columns in the board
for ( int column = 0; column < board[ row ].length; column++ )
// create square
board[ row ][ column ] = new Square( " ", row * 3 + column );
boardPanel.add( board[ row ][ column ] ); // add square
} // end inner for
} // end outer for
idField = new JTextField(); // set up textfield
idField.setEditable( false );
add( idField, BorderLayout.NORTH );
panel2 = new JPanel(); // set up panel to contain boardPanel
btnNew = new JButton("New Game");
panel2.add(btnNew, BorderLayout.NORTH);
panel2.add( boardPanel, BorderLayout.CENTER ); // add board panel
add( panel2, BorderLayout.CENTER ); // add container panel
btnNew.setEnabled(false);
btnNew.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
newGame();
setSize( 300, 225 ); // set size of window
setVisible( true ); // show window
startClient();
} // end TicTacToeClient constructor
// start the client thread
public void startClient()
try // connect to server, get streams and start outputThread
// make connection to server
connection = new Socket(
InetAddress.getByName( ticTacToeHost ), 12345 );
// get streams for input and output
input = new Scanner( connection.getInputStream() );
output = new Formatter( connection.getOutputStream() );
} // end try
catch ( IOException ioException )
ioException.printStackTrace();
} // end catch
// create and start worker thread for this client
ExecutorService worker = Executors.newFixedThreadPool( 1 );
worker.execute( this ); // execute client
} // end method startClient
// control thread that allows continuous update of displayArea
public void run()
myMark = input.nextLine(); // get player's mark (X or O)
SwingUtilities.invokeLater(
new Runnable()
public void run()
// display player's mark
idField.setText( "You are player \"" + myMark + "\"" );
} // end method run
} // end anonymous inner class
); // end call to SwingUtilities.invokeLater
myTurn = ( myMark.equals( X_MARK ) ); // determine if client's turn
// receive messages sent to client and output them
while ( true )
if ( input.hasNextLine() )
processMessage( input.nextLine() );
} // end while
} // end method run
// process messages received by client
private void processMessage( String message )
// valid move occurred
if ( message.equals( "Valid move." ) )
displayMessage( "Valid move, please wait.\n" );
setMark( currentSquare, myMark ); // set mark in square
} // end if
else if ( message.equals( "Invalid move, try again" ) )
displayMessage( message + "\n" ); // display invalid move
myTurn = true; // still this client's turn
} // end else if
else if ( message.equals( "Opponent moved" ) )
int location = input.nextInt(); // get move location
input.nextLine(); // skip newline after int location
int row = location / 3; // calculate row
int column = location % 3; // calculate column
setMark( board[ row ][ column ],
( myMark.equals( X_MARK ) ? O_MARK : X_MARK ) ); // mark move
displayMessage( "Opponent moved. Your turn.\n" );
myTurn = true; // now this client's turn
} // end else if
//Game Over #*********Here**********#
else if ( message.equals( "no winner, you loose" ) )
btnNew.setEnabled(true);
myTurn = false;
} // end else if
else if ( message.equals( "Player X wins" ) ||
message.equals( "Player X wins, you loose" ) )
btnNew.setEnabled(true);
myTurn = false;
} // end else if
else if ( message.equals( "Player O wins" ) ||
message.equals( "Player O wins, you loose" ) )
btnNew.setEnabled(true);
myTurn = false;
} // end else if
else
displayMessage( message + "\n" ); // display the message
} // end method processMessage
//start a new game here
private void newGame()
// manipulate outputArea in event-dispatch thread
private void displayMessage( final String messageToDisplay )
SwingUtilities.invokeLater(
new Runnable()
public void run()
displayArea.append( messageToDisplay ); // updates output
} // end method run
} // end inner class
); // end call to SwingUtilities.invokeLater
} // end method displayMessage
// utility method to set mark on board in event-dispatch thread
private void setMark( final Square squareToMark, final String mark )
SwingUtilities.invokeLater(
new Runnable()
public void run()
squareToMark.setMark( mark ); // set mark in square
} // end method run
} // end anonymous inner class
); // end call to SwingUtilities.invokeLater
} // end method setMark
// send message to server indicating clicked square
public void sendClickedSquare( int location )
// if it is my turn
if ( myTurn )
output.format( "%d\n", location ); // send location to server
output.flush();
myTurn = false; // not my turn anymore
} // end if
} // end method sendClickedSquare
// set current Square
public void setCurrentSquare( Square square )
currentSquare = square; // set current square to argument
} // end method setCurrentSquare
// private inner class for the squares on the board
private class Square extends JPanel
private String mark; // mark to be drawn in this square
private int location; // location of square
public Square( String squareMark, int squareLocation )
mark = squareMark; // set mark for this square
location = squareLocation; // set location of this square
addMouseListener(
new MouseAdapter() {
public void mouseReleased( MouseEvent e )
setCurrentSquare( Square.this ); // set current square
// send location of this square
sendClickedSquare( getSquareLocation() );
} // end method mouseReleased
} // end anonymous inner class
); // end call to addMouseListener
} // end Square constructor
// return preferred size of Square
public Dimension getPreferredSize()
return new Dimension( 30, 30 ); // return preferred size
} // end method getPreferredSize
// return minimum size of Square
public Dimension getMinimumSize()
return getPreferredSize(); // return preferred size
} // end method getMinimumSize
// set mark for Square
public void setMark( String newMark )
mark = newMark; // set mark of square
repaint(); // repaint square
} // end method setMark
// return Square location
public int getSquareLocation()
return location; // return location of square
} // end method getSquareLocation
// draw Square
public void paintComponent( Graphics g )
super.paintComponent( g );
g.drawRect( 0, 0, 29, 29 ); // draw square
g.drawString( mark, 11, 20 ); // draw mark
} // end method paintComponent
} // end inner-class Square
} // end class TicTacToeClient
Please any kind of help will be appreciated.
HELP!!!I would be happy to help you, but I've decided not to contribute here anymore because of the poor way in which this site is being administered.
Others are still helping, but more may leave if things don't improve. May I recommend devshed or javaranch?
http://www.devshed.com/
http://www.javaranch.com/
If you would like to complain to the amdins of this forum, either click the "Report Abuse" link or the "Feedback" link. -
Hi
I used Deitel's code of TicTacToe program that creats a server and have 2 clients playing TicTacToe. When the game is over one of the client has to click on new game and a new game will begin. I don't know how to do this.
Please Help.
Here's the code for the server
import java.awt.BorderLayout;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
import java.util.Formatter;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.Condition;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class TicTacToeServer extends JFrame
private String[] board = new String[ 9 ]; // tic-tac-toe board
private JTextArea outputArea; // for outputting moves
private Player[] players; // array of Players
private ServerSocket server; // server socket to connect with clients
private int currentPlayer; // keeps track of player with current move
private final static int PLAYER_X = 0; // constant for first player
private final static int PLAYER_O = 1; // constant for second player
private final static String[] MARKS = { "X", "O" }; // array of marks
private ExecutorService runGame; // will run players
private Lock gameLock; // to lock game for synchronization
private Condition otherPlayerConnected; // to wait for other player
private Condition otherPlayerTurn; // to wait for other player's turn
// set up tic-tac-toe server and GUI that displays messages
public TicTacToeServer()
super( "Tic-Tac-Toe Server" ); // set title of window
// create ExecutorService with a thread for each player
runGame = Executors.newFixedThreadPool( 2 );
gameLock = new ReentrantLock(); // create lock for game
// condition variable for both players being connected
otherPlayerConnected = gameLock.newCondition();
// condition variable for the other player's turn
otherPlayerTurn = gameLock.newCondition();
for ( int i = 0; i < 9; i++ )
board[ i ] = new String( "" ); // create tic-tac-toe board
players = new Player[ 2 ]; // create array of players
currentPlayer = PLAYER_X; // set current player to first player
try
server = new ServerSocket( 12345, 2 ); // set up ServerSocket
} // end try
catch ( IOException ioException )
ioException.printStackTrace();
System.exit( 1 );
} // end catch
outputArea = new JTextArea(); // create JTextArea for output
add( outputArea, BorderLayout.CENTER );
outputArea.setText( "Server awaiting connections\n" );
setSize( 300, 300 ); // set size of window
setVisible( true ); // show window
} // end TicTacToeServer constructor
// wait for two connections so game can be played
public void execute()
// wait for each client to connect
for ( int i = 0; i < players.length; i++ )
try // wait for connection, create Player, start runnable
players[ i ] = new Player( server.accept(), i );
runGame.execute( players[ i ] ); // execute player runnable
} // end try
catch ( IOException ioException )
ioException.printStackTrace();
System.exit( 1 );
} // end catch
} // end for
gameLock.lock(); // lock game to signal player X's thread
try
players[ PLAYER_X ].setSuspended( false ); // resume player X
otherPlayerConnected.signal(); // wake up player X's thread
} // end try
finally
gameLock.unlock(); // unlock game after signalling player X
} // end finally
} // end method execute
// display message in outputArea
private void displayMessage( final String messageToDisplay )
// display message from event-dispatch thread of execution
SwingUtilities.invokeLater(
new Runnable()
public void run() // updates outputArea
outputArea.append( messageToDisplay ); // add message
} // end method run
} // end inner class
); // end call to SwingUtilities.invokeLater
} // end method displayMessage
// determine if move is valid
public boolean validateAndMove( int location, int player )
// while not current player, must wait for turn
while ( player != currentPlayer )
gameLock.lock(); // lock game to wait for other player to go
try
otherPlayerTurn.await(); // wait for player's turn
} // end try
catch ( InterruptedException exception )
exception.printStackTrace();
} // end catch
finally
gameLock.unlock(); // unlock game after waiting
} // end finally
} // end while
// if location not occupied, make move
if ( !isOccupied( location ) )
board[ location ] = MARKS[ currentPlayer ]; // set move on board
currentPlayer = ( currentPlayer + 1 ) % 2; // change player
// let new current player know that move occurred
players[ currentPlayer ].otherPlayerMoved( location );
gameLock.lock(); // lock game to signal other player to go
try
otherPlayerTurn.signal(); // signal other player to continue
} // end try
finally
gameLock.unlock(); // unlock game after signaling
} // end finally
return true; // notify player that move was valid
} // end if
else // move was not valid
return false; // notify player that move was invalid
} // end method validateAndMove
// determine whether location is occupied
public boolean isOccupied( int location )
if ( board[ location ].equals( MARKS[ PLAYER_X ] ) ||
board [ location ].equals( MARKS[ PLAYER_O ] ) )
return true; // location is occupied
else
return false; // location is not occupied
} // end method isOccupied
// place code in this method to determine whether game over
public boolean isGameOver()
if( ( !board[ 0 ].equals( "" ) &&
!board[ 1 ].equals( "" ) &&
!board[ 2 ].equals( "" ) &&
!board[ 3 ].equals( "" ) &&
!board[ 4 ].equals( "" ) &&
!board[ 5 ].equals( "" ) &&
!board[ 6 ].equals( "" ) &&
!board[ 7 ].equals( "" ) &&
!board[ 8 ].equals( "" ) ) )
players[0].gameOver("Game Over, no winner");
players[1].gameOver("Game Over, no winner");
return true;
else if( board[ 0 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 1 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 2 ].equals( MARKS[ PLAYER_X ] ) )
players[0].gameOver("Player X wins");
players[1].gameOver("Player X wins");
return true;
else if( board [ 0 ].equals( MARKS[ PLAYER_O ]) &&
board [ 1 ].equals( MARKS[ PLAYER_O ]) &&
board [ 2 ].equals( MARKS[ PLAYER_O ]) )
players[0].gameOver("Player O wins");
players[1].gameOver("Player O wins");
return true;
else if( board[ 3 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 4 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 5 ].equals( MARKS[ PLAYER_X ] ) )
players[0].gameOver("Player X wins");
players[1].gameOver("Player X wins");
return true;
else if( board [ 3 ].equals( MARKS[ PLAYER_O ]) &&
board [ 4 ].equals( MARKS[ PLAYER_O ]) &&
board [ 5 ].equals( MARKS[ PLAYER_O ]) )
players[0].gameOver("Player O wins");
players[1].gameOver("Player O wins");
return true;
else if( board[ 6 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 7 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 8 ].equals( MARKS[ PLAYER_X ] ) )
players[0].gameOver("Player X wins");
players[1].gameOver("Player X wins");
return true;
else if( board [ 6 ].equals( MARKS[ PLAYER_O ]) &&
board [ 7 ].equals( MARKS[ PLAYER_O ]) &&
board [ 8 ].equals( MARKS[ PLAYER_O ]) )
players[0].gameOver("Player O wins");
players[1].gameOver("Player O wins");
return true;
else if( board[ 0 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 3 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 6 ].equals( MARKS[ PLAYER_X ] ) )
players[0].gameOver("Player X wins");
players[1].gameOver("Player X wins");
return true;
else if( board[ 0 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 3 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 6 ].equals( MARKS[ PLAYER_X ] ) )
players[0].gameOver("Player O wins");
players[1].gameOver("Player O wins");
return true;
else if( board[ 1 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 4 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 7 ].equals( MARKS[ PLAYER_X ] ) )
players[0].gameOver("Player X wins");
players[1].gameOver("Player X wins");
return true;
else if( board [ 1 ].equals( MARKS[ PLAYER_O ]) &&
board [ 4 ].equals( MARKS[ PLAYER_O ]) &&
board [ 7 ].equals( MARKS[ PLAYER_O ]) )
players[0].gameOver("Player O wins");
players[1].gameOver("Player O wins");
return true;
else if( board[ 2 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 5 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 8 ].equals( MARKS[ PLAYER_X ] ) )
players[0].gameOver("Player X wins");
players[1].gameOver("Player X wins");
return true;
else if( board [ 2 ].equals( MARKS[ PLAYER_O ]) &&
board [ 5 ].equals( MARKS[ PLAYER_O ]) &&
board [ 8 ].equals( MARKS[ PLAYER_O ]) )
players[0].gameOver("Player O wins");
players[1].gameOver("Player O wins");
return true;
else if( board[ 0 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 4 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 8 ].equals( MARKS[ PLAYER_X ] ) )
players[0].gameOver("Player X wins");
players[1].gameOver("Player X wins");
return true;
else if( board [ 0 ].equals( MARKS[ PLAYER_O ]) &&
board [ 4 ].equals( MARKS[ PLAYER_O ]) &&
board [ 8 ].equals( MARKS[ PLAYER_O ]) )
players[0].gameOver("Player O wins");
players[1].gameOver("Player O wins");
return true;
else if( board[ 2 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 4 ].equals( MARKS[ PLAYER_X ] ) &&
board[ 8 ].equals( MARKS[ PLAYER_X ] ) )
players[0].gameOver("Player X wins");
players[1].gameOver("Player X wins");
return true;
else if( board [ 2 ].equals( MARKS[ PLAYER_O ]) &&
board [ 4 ].equals( MARKS[ PLAYER_O ]) &&
board [ 8 ].equals( MARKS[ PLAYER_O ]) )
players[0].gameOver("Player O wins");
players[1].gameOver("Player O wins");
return true;
else
return false; // this is left as an exercise
} // end method isGameOver
// private inner class Player manages each Player as a runnable
private class Player implements Runnable
private Socket connection; // connection to client
private Scanner input; // input from client
private Formatter output; // output to client
private int playerNumber; // tracks which player this is
private String mark; // mark for this player
private boolean suspended = true; // whether thread is suspended
// set up Player thread
public Player( Socket socket, int number )
playerNumber = number; // store this player's number
mark = MARKS[ playerNumber ]; // specify player's mark
connection = socket; // store socket for client
try // obtain streams from Socket
input = new Scanner( connection.getInputStream() );
output = new Formatter( connection.getOutputStream() );
} // end try
catch ( IOException ioException )
ioException.printStackTrace();
System.exit( 1 );
} // end catch
} // end Player constructor
// send message that other player moved
public void otherPlayerMoved( int location )
output.format( "Opponent moved\n" );
output.format( "%d\n", location ); // send location of move
output.flush(); // flush output
} // end method otherPlayerMoved
// control thread's execution
public void run()
// send client its mark (X or O), process messages from client
try
displayMessage( "Player " + mark + " connected\n" );
output.format( "%s\n", mark ); // send player's mark
output.flush(); // flush output
// if player X, wait for another player to arrive
if ( playerNumber == PLAYER_X )
output.format( "%s\n%s", "Player X connected",
"Waiting for another player\n" );
output.flush(); // flush output
gameLock.lock(); // lock game to wait for second player
try
while( suspended )
otherPlayerConnected.await(); // wait for player O
} // end while
} // end try
catch ( InterruptedException exception )
exception.printStackTrace();
} // end catch
finally
gameLock.unlock(); // unlock game after second player
} // end finally
// send message that other player connected
output.format( "Other player connected. Your move.\n" );
output.flush(); // flush output
} // end if
else
output.format( "Player O connected, please wait\n" );
output.flush(); // flush output
} // end else
// while game not over
while ( !isGameOver() )
int location = 0; // initialize move location
if ( input.hasNext() )
location = input.nextInt(); // get move location
// check for valid move
if ( validateAndMove( location, playerNumber ) )
displayMessage( "\nlocation: " + location );
output.format( "Valid move.\n" ); // notify client
output.flush(); // flush output
} // end if
else // move was invalid
output.format( "Invalid move, try again\n" );
output.flush(); // flush output
} // end else
} // end while
} // end try
finally
try
connection.close(); // close connection to client
} // end try
catch ( IOException ioException )
ioException.printStackTrace();
System.exit( 1 );
} // end catch
} // end finally
} // end method run
// set whether or not thread is suspended
public void setSuspended( boolean status )
suspended = status; // set value of suspended
} // end method setSuspended
public void gameOver(String msg)
if(msg.equals("Game Over, no winner"))
if ( playerNumber == PLAYER_X )
output.format( "no winner, you loose\n" );
output.flush(); // flush output
} // end if
else
output.format( "no winner, you loose\n" );
output.flush(); // flush output
} // end else
gameLock.lock();
else if(msg.equals("Player X wins"))
if ( playerNumber == PLAYER_X )
output.format(msg + "\n" );
output.flush(); // flush output
} // end if
else
output.format(msg + ", you loose\n" );
output.flush(); // flush output
} // end else
gameLock.lock();
else if(msg.equals("Player O wins"))
if ( playerNumber == PLAYER_X )
//players[1].
output.format(msg + ", you loose\n" );
output.flush(); // flush output
} // end if
else
output.format(msg + "\n" );
output.flush(); // flush output
} // end else
gameLock.lock();
else
} // end class Player
} // end class TicTacToeServer
*****and here's the code for the client
// Fig. 24.15: TicTacToeClient.java
// Client that let a user play Tic-Tac-Toe with another across a network.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.*;
import java.net.Socket;
import java.net.InetAddress;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
import java.util.Formatter;
import java.util.Scanner;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
public class TicTacToeClient extends JFrame implements Runnable
private JTextField idField; // textfield to display player's mark
private JTextArea displayArea; // JTextArea to display output
private JPanel boardPanel; // panel for tic-tac-toe board
private JPanel panel2; // panel to hold board
private JButton btnNew;
private Square board[][]; // tic-tac-toe board
private Square currentSquare; // current square
private Socket connection; // connection to server
private Scanner input; // input from server
private Formatter output; // output to server
private String ticTacToeHost; // host name for server
private String myMark; // this client's mark
private boolean myTurn; // determines which client's turn it is
private final String X_MARK = "X"; // mark for first client
private final String O_MARK = "O"; // mark for second client
// set up user-interface and board
public TicTacToeClient( String host )
ticTacToeHost = host; // set name of server
displayArea = new JTextArea( 4, 30 ); // set up JTextArea
displayArea.setEditable( false );
add( new JScrollPane( displayArea ), BorderLayout.SOUTH );
boardPanel = new JPanel(); // set up panel for squares in board
boardPanel.setLayout( new GridLayout( 3, 3, 0, 0 ) );
board = new Square[ 3 ][ 3 ]; // create board
// loop over the rows in the board
for ( int row = 0; row < board.length; row++ )
// loop over the columns in the board
for ( int column = 0; column < board[ row ].length; column++ )
// create square
board[ row ][ column ] = new Square( " ", row * 3 + column );
boardPanel.add( board[ row ][ column ] ); // add square
} // end inner for
} // end outer for
idField = new JTextField(); // set up textfield
idField.setEditable( false );
add( idField, BorderLayout.NORTH );
panel2 = new JPanel(); // set up panel to contain boardPanel
btnNew = new JButton("New Game");
panel2.add(btnNew, BorderLayout.NORTH);
panel2.add( boardPanel, BorderLayout.CENTER ); // add board panel
add( panel2, BorderLayout.CENTER ); // add container panel
btnNew.setEnabled(false);
btnNew.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
newGame();
setSize( 300, 225 ); // set size of window
setVisible( true ); // show window
startClient();
} // end TicTacToeClient constructor
// start the client thread
public void startClient()
try // connect to server, get streams and start outputThread
// make connection to server
connection = new Socket(
InetAddress.getByName( ticTacToeHost ), 12345 );
// get streams for input and output
input = new Scanner( connection.getInputStream() );
output = new Formatter( connection.getOutputStream() );
} // end try
catch ( IOException ioException )
ioException.printStackTrace();
} // end catch
// create and start worker thread for this client
ExecutorService worker = Executors.newFixedThreadPool( 1 );
worker.execute( this ); // execute client
} // end method startClient
// control thread that allows continuous update of displayArea
public void run()
myMark = input.nextLine(); // get player's mark (X or O)
SwingUtilities.invokeLater(
new Runnable()
public void run()
// display player's mark
idField.setText( "You are player \"" + myMark + "\"" );
} // end method run
} // end anonymous inner class
); // end call to SwingUtilities.invokeLater
myTurn = ( myMark.equals( X_MARK ) ); // determine if client's turn
// receive messages sent to client and output them
while ( true )
if ( input.hasNextLine() )
processMessage( input.nextLine() );
} // end while
} // end method run
// process messages received by client
private void processMessage( String message )
// valid move occurred
if ( message.equals( "Valid move." ) )
displayMessage( "Valid move, please wait.\n" );
setMark( currentSquare, myMark ); // set mark in square
} // end if
else if ( message.equals( "Invalid move, try again" ) )
displayMessage( message + "\n" ); // display invalid move
myTurn = true; // still this client's turn
} // end else if
else if ( message.equals( "Opponent moved" ) )
int location = input.nextInt(); // get move location
input.nextLine(); // skip newline after int location
int row = location / 3; // calculate row
int column = location % 3; // calculate column
setMark( board[ row ][ column ],
( myMark.equals( X_MARK ) ? O_MARK : X_MARK ) ); // mark move
displayMessage( "Opponent moved. Your turn.\n" );
myTurn = true; // now this client's turn
} // end else if
//Game Over #*********Here**********#
else if ( message.equals( "no winner, you loose" ) )
btnNew.setEnabled(true);
myTurn = false;
} // end else if
else if ( message.equals( "Player X wins" ) ||
message.equals( "Player X wins, you loose" ) )
btnNew.setEnabled(true);
myTurn = false;
} // end else if
else if ( message.equals( "Player O wins" ) ||
message.equals( "Player O wins, you loose" ) )
btnNew.setEnabled(true);
myTurn = false;
} // end else if
else
displayMessage( message + "\n" ); // display the message
} // end method processMessage
//start a new game here
private void newGame()
// manipulate outputArea in event-dispatch thread
private void displayMessage( final String messageToDisplay )
SwingUtilities.invokeLater(
new Runnable()
public void run()
displayArea.append( messageToDisplay ); // updates output
} // end method run
} // end inner class
); // end call to SwingUtilities.invokeLater
} // end method displayMessage
// utility method to set mark on board in event-dispatch thread
private void setMark( final Square squareToMark, final String mark )
SwingUtilities.invokeLater(
new Runnable()
public void run()
squareToMark.setMark( mark ); // set mark in square
} // end method run
} // end anonymous inner class
); // end call to SwingUtilities.invokeLater
} // end method setMark
// send message to server indicating clicked square
public void sendClickedSquare( int location )
// if it is my turn
if ( myTurn )
output.format( "%d\n", location ); // send location to server
output.flush();
myTurn = false; // not my turn anymore
} // end if
} // end method sendClickedSquare
// set current Square
public void setCurrentSquare( Square square )
currentSquare = square; // set current square to argument
} // end method setCurrentSquare
// private inner class for the squares on the board
private class Square extends JPanel
private String mark; // mark to be drawn in this square
private int location; // location of square
public Square( String squareMark, int squareLocation )
mark = squareMark; // set mark for this square
location = squareLocation; // set location of this square
addMouseListener(
new MouseAdapter() {
public void mouseReleased( MouseEvent e )
setCurrentSquare( Square.this ); // set current square
// send location of this square
sendClickedSquare( getSquareLocation() );
} // end method mouseReleased
} // end anonymous inner class
); // end call to addMouseListener
} // end Square constructor
// return preferred size of Square
public Dimension getPreferredSize()
return new Dimension( 30, 30 ); // return preferred size
} // end method getPreferredSize
// return minimum size of Square
public Dimension getMinimumSize()
return getPreferredSize(); // return preferred size
} // end method getMinimumSize
// set mark for Square
public void setMark( String newMark )
mark = newMark; // set mark of square
repaint(); // repaint square
} // end method setMark
// return Square location
public int getSquareLocation()
return location; // return location of square
} // end method getSquareLocation
// draw Square
public void paintComponent( Graphics g )
super.paintComponent( g );
g.drawRect( 0, 0, 29, 29 ); // draw square
g.drawString( mark, 11, 20 ); // draw mark
} // end method paintComponent
} // end inner-class Square
} // end class TicTacToeClient
Please any kind of help will be appreciated.
HELP!!!This isn't a code writing service.
Start your own thread, rather than reviving one that is very old. And ask a question: that is, actually describe in what respect your program is not working. Often the most effective way of doing this is to post some code whose runtime behaviour is not what you expect or intend. If you do post code make sure it's brief and to the point (ie just illustrates the problem you are having). To make sure your code is readable when you post it here use the code tags: put {code} at the start of your code and the same thing again at the end. -
Multithread TicTacToe Server Problem
I'm having some problems with finishing up a tic tac toe server and it's driving me crazy. I'm hoping someone can give me some hints or help out with this. All of the code is written for the server which allows 2 clients to connect, but the code for determining if the game is won needs to be finished up.
I've got the method for determining if the game is over done, that part is easy, and I'm able to send a message to the client who wins when they place the winning marker and end the game for them, but currently the next player gets to place one more marker before being signaled that the game is over. I worked on this forever and I think I'm just missing something simple that I hope someone can help me with. Here's the code:
Line 180 in TicTacToeServer.java is where I test for the win
Line 304 in TicTacToeServer.java is where the clients exit the main while loop after determining that the game is won and I send a message letting them know that the game is won
Server Code:
TicTacToeServerTest.java
// Tests the TicTacToeServer.
import javax.swing.JFrame;
public class TicTacToeServerTest
public static void main( String args[] )
TicTacToeServer application = new TicTacToeServer();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
application.execute();
} // end main
} // end class TicTacToeServerTest
TicTacToeServer.java
// This class maintains a game of Tic-Tac-Toe for two clients.
import javax.swing.JOptionPane;
import java.awt.BorderLayout;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
import java.util.Formatter;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.Condition;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class TicTacToeServer extends JFrame
private String[] board = new String[ 9 ]; // tic-tac-toe board
private JTextArea outputArea; // for outputting moves
private Player[] players; // array of Players
private ServerSocket server; // server socket to connect with clients
private int currentPlayer; // keeps track of player with current move
private final static int PLAYER_X = 0; // constant for first player
private final static int PLAYER_O = 1; // constant for second player
private final static String[] MARKS = { "X", "O" }; // array of marks
private ExecutorService runGame; // will run players
private Lock gameLock; // to lock game for synchronization
private Condition otherPlayerConnected; // to wait for other player
private Condition otherPlayerTurn; // to wait for other player's turn
private int winner = 2;
// set up tic-tac-toe server and GUI that displays messages
public TicTacToeServer()
super( "Tic-Tac-Toe Server" ); // set title of window
// create ExecutorService with a thread for each player
runGame = Executors.newFixedThreadPool( 2 );
gameLock = new ReentrantLock(); // create lock for game
// condition variable for both players being connected
otherPlayerConnected = gameLock.newCondition();
// condition variable for the other player's turn
otherPlayerTurn = gameLock.newCondition();
for ( int i = 0; i < 9; i++ )
board[ i ] = new String( "" ); // create tic-tac-toe board
players = new Player[ 2 ]; // create array of players
currentPlayer = PLAYER_X; // set current player to first player
try
server = new ServerSocket( 12345, 2 ); // set up ServerSocket
} // end try
catch ( IOException ioException )
ioException.printStackTrace();
System.exit( 1 );
} // end catch
outputArea = new JTextArea(); // create JTextArea for output
add( outputArea, BorderLayout.CENTER );
outputArea.setText( "Server awaiting connections\n" );
setSize( 300, 300 ); // set size of window
setVisible( true ); // show window
} // end TicTacToeServer constructor
// wait for two connections so game can be played
public void execute()
// wait for each client to connect
for ( int i = 0; i < players.length; i++ )
try // wait for connection, create Player, start runnable
players[ i ] = new Player( server.accept(), i );
runGame.execute( players[ i ] ); // execute player runnable
} // end try
catch ( IOException ioException )
ioException.printStackTrace();
System.exit( 1 );
} // end catch
} // end for
gameLock.lock(); // lock game to signal player X's thread
try
players[ PLAYER_X ].setSuspended( false ); // resume player X
otherPlayerConnected.signal(); // wake up player X's thread
} // end try
finally
gameLock.unlock(); // unlock game after signalling player X
} // end finally
} // end method execute
// display message in outputArea
private void displayMessage( final String messageToDisplay )
// display message from event-dispatch thread of execution
SwingUtilities.invokeLater(
new Runnable()
public void run() // updates outputArea
outputArea.append( messageToDisplay ); // add message
} // end method run
} // end inner class
); // end call to SwingUtilities.invokeLater
} // end method displayMessage
// determine if move is valid
public boolean validateAndMove( int location, int player )
// while not current player, must wait for turn
while ( player != currentPlayer )
gameLock.lock(); // lock game to wait for other player to go
try
otherPlayerTurn.await(); // wait for player's turn
} // end try
catch ( InterruptedException exception )
exception.printStackTrace();
} // end catch
finally
gameLock.unlock(); // unlock game after waiting
} // end finally
} // end while
// if location not occupied, make move
if ( !isOccupied( location ) )
board[ location ] = MARKS[ currentPlayer ]; // set move on board
currentPlayer = ( currentPlayer + 1 ) % 2; // change player
// let new current player know that move occurred
players[ currentPlayer ].otherPlayerMoved( location );
gameLock.lock(); // lock game to signal other player to go
try
otherPlayerTurn.signal(); // signal other player to continue
} // end try
finally
gameLock.unlock(); // unlock game after signaling
} // end finally
return true; // notify player that move was valid
} // end if
else // move was not valid
return false; // notify player that move was invalid
} // end method validateAndMove
// determine whether location is occupied
public boolean isOccupied( int location )
if ( board[ location ].equals( MARKS[ PLAYER_X ] ) ||
board [ location ].equals( MARKS[ PLAYER_O ] ) )
return true; // location is occupied
else
return false; // location is not occupied
} // end method isOccupied
// place code in this method to determine whether game over
public boolean isGameOver()
for (int x = 0; x < 2; x++)
if ((board[0].equals(MARKS[x]) && board[1].equals(MARKS[x]) && board[2].equals(MARKS[x])) ||
(board[3].equals(MARKS[x]) && board[4].equals(MARKS[x]) && board[5].equals(MARKS[x])) ||
(board[6].equals(MARKS[x]) && board[7].equals(MARKS[x]) && board[8].equals(MARKS[x])) ||
(board[0].equals(MARKS[x]) && board[4].equals(MARKS[x]) && board[8].equals(MARKS[x])) ||
(board[6].equals(MARKS[x]) && board[4].equals(MARKS[x]) && board[2].equals(MARKS[x])) ||
(board[0].equals(MARKS[x]) && board[3].equals(MARKS[x]) && board[6].equals(MARKS[x])) ||
(board[1].equals(MARKS[x]) && board[4].equals(MARKS[x]) && board[7].equals(MARKS[x])) ||
(board[2].equals(MARKS[x]) && board[5].equals(MARKS[x]) && board[8].equals(MARKS[x]))
winner = x;
return true;
return false; // this is left as an exercise
} // end method isGameOver
// private inner class Player manages each Player as a runnable
private class Player implements Runnable
private Socket connection; // connection to client
private Scanner input; // input from client
private Formatter output; // output to client
private int playerNumber; // tracks which player this is
private String mark; // mark for this player
private boolean suspended = true; // whether thread is suspended
// set up Player thread
public Player( Socket socket, int number )
playerNumber = number; // store this player's number
mark = MARKS[ playerNumber ]; // specify player's mark
connection = socket; // store socket for client
try // obtain streams from Socket
input = new Scanner( connection.getInputStream() );
output = new Formatter( connection.getOutputStream() );
} // end try
catch ( IOException ioException )
ioException.printStackTrace();
System.exit( 1 );
} // end catch
} // end Player constructor
// send message that other player moved
public void otherPlayerMoved( int location )
output.format( "Opponent moved\n" );
output.format( "%d\n", location ); // send location of move
output.flush(); // flush output
} // end method otherPlayerMoved
// control thread's execution
public void run()
// send client its mark (X or O), process messages from client
try
displayMessage( "Player " + mark + " connected\n" );
output.format( "%s\n", mark ); // send player's mark
output.flush(); // flush output
// if player X, wait for another player to arrive
if ( playerNumber == PLAYER_X )
output.format( "%s\n%s", "Player X connected",
"Waiting for another player\n" );
output.flush(); // flush output
gameLock.lock(); // lock game to wait for second player
try
while( suspended )
otherPlayerConnected.await(); // wait for player O
} // end while
} // end try
catch ( InterruptedException exception )
exception.printStackTrace();
} // end catch
finally
gameLock.unlock(); // unlock game after second player
} // end finally
// send message that other player connected
output.format( "Other player connected. Your move.\n" );
output.flush(); // flush output
} // end if
else
output.format( "Player O connected, please wait\n" );
output.flush(); // flush output
} // end else
// while game not over
while ( !isGameOver() )
int location = 0; // initialize move location
if ( input.hasNext() )
location = input.nextInt(); // get move location
// check for valid move
if ( validateAndMove( location, playerNumber ) )
displayMessage( "\nlocation: " + location );
output.format( "Valid move.\n" ); // notify client
output.flush(); // flush output
} // end if
else // move was invalid
output.format( "Invalid move, try again\n" );
output.flush(); // flush output
} // end else
} // end while
output.format( "Game Over.\n" ); // notify client
if (winner == 0)
output.format("Winner is X\n");
if (winner == 1)
output.format("Winner is O\n");
output.flush(); // flush output
gameLock.unlock();
} // end try
finally
try
connection.close(); // close connection to client
} // end try
catch ( IOException ioException )
ioException.printStackTrace();
System.exit( 1 );
} // end catch
} // end finally
} // end method run
// set whether or not thread is suspended
public void setSuspended( boolean status )
suspended = status; // set value of suspended
} // end method setSuspended
} // end class Player
} // end class TicTacToeServer
Client Code:
TicTacToeClientTest.java
// Tests the TicTacToeClient class.
import javax.swing.JFrame;
public class TicTacToeClientTest
public static void main( String args[] )
TicTacToeClient application; // declare client application
// if no command line args
if ( args.length == 0 )
application = new TicTacToeClient( "127.0.0.1" ); // localhost
else
application = new TicTacToeClient( args[ 0 ] ); // use args
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
} // end main
} // end class TicTacToeClientTest
TicTacToeClient.java
// Client that let a user play Tic-Tac-Toe with another across a network.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.Socket;
import java.net.InetAddress;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import java.util.Formatter;
import java.util.Scanner;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
public class TicTacToeClient extends JFrame implements Runnable
private JTextField idField; // textfield to display player's mark
private JTextArea displayArea; // JTextArea to display output
private JPanel boardPanel; // panel for tic-tac-toe board
private JPanel panel2; // panel to hold board
private Square board[][]; // tic-tac-toe board
private Square currentSquare; // current square
private Socket connection; // connection to server
private Scanner input; // input from server
private Formatter output; // output to server
private String ticTacToeHost; // host name for server
private String myMark; // this client's mark
private boolean myTurn; // determines which client's turn it is
private final String X_MARK = "X"; // mark for first client
private final String O_MARK = "O"; // mark for second client
// set up user-interface and board
public TicTacToeClient( String host )
ticTacToeHost = host; // set name of server
displayArea = new JTextArea( 4, 30 ); // set up JTextArea
displayArea.setEditable( false );
add( new JScrollPane( displayArea ), BorderLayout.SOUTH );
boardPanel = new JPanel(); // set up panel for squares in board
boardPanel.setLayout( new GridLayout( 3, 3, 0, 0 ) );
board = new Square[ 3 ][ 3 ]; // create board
// loop over the rows in the board
for ( int row = 0; row < board.length; row++ )
// loop over the columns in the board
for ( int column = 0; column < board[ row ].length; column++ )
// create square
board[ row ][ column ] = new Square( " ", row * 3 + column );
boardPanel.add( board[ row ][ column ] ); // add square
} // end inner for
} // end outer for
idField = new JTextField(); // set up textfield
idField.setEditable( false );
add( idField, BorderLayout.NORTH );
panel2 = new JPanel(); // set up panel to contain boardPanel
panel2.add( boardPanel, BorderLayout.CENTER ); // add board panel
add( panel2, BorderLayout.CENTER ); // add container panel
setSize( 300, 225 ); // set size of window
setVisible( true ); // show window
startClient();
} // end TicTacToeClient constructor
// start the client thread
public void startClient()
try // connect to server, get streams and start outputThread
// make connection to server
connection = new Socket(
InetAddress.getByName( ticTacToeHost ), 12345 );
// get streams for input and output
input = new Scanner( connection.getInputStream() );
output = new Formatter( connection.getOutputStream() );
} // end try
catch ( IOException ioException )
ioException.printStackTrace();
} // end catch
// create and start worker thread for this client
ExecutorService worker = Executors.newFixedThreadPool( 1 );
worker.execute( this ); // execute client
} // end method startClient
// control thread that allows continuous update of displayArea
public void run()
myMark = input.nextLine(); // get player's mark (X or O)
SwingUtilities.invokeLater(
new Runnable()
public void run()
// display player's mark
idField.setText( "You are player \"" + myMark + "\"" );
} // end method run
} // end anonymous inner class
); // end call to SwingUtilities.invokeLater
myTurn = ( myMark.equals( X_MARK ) ); // determine if client's turn
// receive messages sent to client and output them
while ( true )
if ( input.hasNextLine() )
processMessage( input.nextLine() );
} // end while
} // end method run
// process messages received by client
private void processMessage( String message )
// valid move occurred
if ( message.equals( "Valid move." ) )
displayMessage( "Valid move, please wait.\n" );
setMark( currentSquare, myMark ); // set mark in square
} // end if
else if ( message.equals( "Invalid move, try again" ) )
displayMessage( message + "\n" ); // display invalid move
myTurn = true; // still this client's turn
} // end else if
else if ( message.equals( "Opponent moved" ) )
int location = input.nextInt(); // get move location
input.nextLine(); // skip newline after int location
int row = location / 3; // calculate row
int column = location % 3; // calculate column
setMark( board[ row ][ column ],
( myMark.equals( X_MARK ) ? O_MARK : X_MARK ) ); // mark move
displayMessage( "Opponent moved. Your turn.\n" );
myTurn = true; // now this client's turn
} // end else if
else
displayMessage( message + "\n" ); // display the message
} // end method processMessage
// manipulate outputArea in event-dispatch thread
private void displayMessage( final String messageToDisplay )
SwingUtilities.invokeLater(
new Runnable()
public void run()
displayArea.append( messageToDisplay ); // updates output
} // end method run
} // end inner class
); // end call to SwingUtilities.invokeLater
} // end method displayMessage
// utility method to set mark on board in event-dispatch thread
private void setMark( final Square squareToMark, final String mark )
SwingUtilities.invokeLater(
new Runnable()
public void run()
squareToMark.setMark( mark ); // set mark in square
} // end method run
} // end anonymous inner class
); // end call to SwingUtilities.invokeLater
} // end method setMark
// send message to server indicating clicked square
public void sendClickedSquare( int location )
// if it is my turn
if ( myTurn )
output.format( "%d\n", location ); // send location to server
output.flush();
myTurn = false; // not my turn anymore
} // end if
} // end method sendClickedSquare
// set current Square
public void setCurrentSquare( Square square )
currentSquare = square; // set current square to argument
} // end method setCurrentSquare
// private inner class for the squares on the board
private class Square extends JPanel
private String mark; // mark to be drawn in this square
private int location; // location of square
public Square( String squareMark, int squareLocation )
mark = squareMark; // set mark for this square
location = squareLocation; // set location of this square
addMouseListener(
new MouseAdapter() {
public void mouseReleased( MouseEvent e )
setCurrentSquare( Square.this ); // set current square
// send location of this square
sendClickedSquare( getSquareLocation() );
} // end method mouseReleased
} // end anonymous inner class
); // end call to addMouseListener
} // end Square constructor
// return preferred size of Square
public Dimension getPreferredSize()
return new Dimension( 30, 30 ); // return preferred size
} // end method getPreferredSize
// return minimum size of Square
public Dimension getMinimumSize()
return getPreferredSize(); // return preferred size
} // end method getMinimumSize
// set mark for Square
public void setMark( String newMark )
mark = newMark; // set mark of square
repaint(); // repaint square
} // end method setMark
// return Square location
public int getSquareLocation()
return location; // return location of square
} // end method getSquareLocation
// draw Square
public void paintComponent( Graphics g )
super.paintComponent( g );
g.drawRect( 0, 0, 29, 29 ); // draw square
g.drawString( mark, 11, 20 ); // draw mark
} // end method paintComponent
} // end inner-class Square
} // end class TicTacToeClientI'll look into doing it that way... One thing I don't understand is that when the winning player places it's final marker and gets the game over message the other player gets passed the Opponent moved message. So shouldn't I be able to pass a Game Over message to the other player after sending the Game Over message to the winning player? I'm not sure where in the code I'd need to put the output statement or what code I'd use to send it to the losing player instead of the winning player. I'm fairly new to threading and working on this for school, the book is not very much help in this area, so excuse my ignorance. Is it possible to send a message to the losing client right after sending one to the winning client after the main while loop exits around line 309 of TicTacToeServer.java? Or is this not possible because of how threading works?
-
Populating Swing JList using SQL Database
Sup peeps, im trying to to populate a JList using the entries in a table in a database i created.
package networks;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.PrintWriter;
import java.sql.*;
public class Contestantlist extends javax.swing.JFrame {
/** Creates new form contestantList */
public Contestantlist() {
initComponents();
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
try
// Load driver's class, inilialize, register with DriverManager
//Class.forName("oracle.jdbc.driver.OracleDriver");
Class.forName("org.gjt.mm.mysql.Driver");
catch (ClassNotFoundException e)
System.out.println("Unable to load driver class");
return;
ResultSet rs = null;
try
// Call DriverManager's methods (all are static)
// To print log on sysout
//DriverManager.setLogStream(System.out); //JDBC 1.x driver
// DriverManager.setLogWriter(new PrintWriter(System.out) );
// Connect to database. DriverManager loads each registered driver
// in turn until one can handle the database URL format
//Connection con = DriverManager.getConnection(
// "jdbc:oracle:thin:@host.domain.com:1521:db_name"
// ,"scott","tiger");
// Connection con = DriverManager.getConnection("jdbc:mySql://localhost:3306/Contest","root","blink182");
// Get the DatabaseMetaData object to display database info
// DatabaseMetaData dmd = con.getMetaData();
// Statement stmt = con.createStatement();
// String sql;
// sql = "SELECT Username FROM Contestant WHERE Username IS NOT NULL";
// rs = stmt.executeQuery(sql); //throws SQLExecption if fails
// printResultSet(rs);
DriverManager.setLogWriter(new PrintWriter(System.out) );
Connection con = DriverManager.getConnection("jdbc:mySql://localhost:3306/Contest","root","blink182");
// Get the DatabaseMetaData object to display database info
DatabaseMetaData dmd = con.getMetaData();
String sql;
Statement stmt = con.createStatement();
sql = "SELECT Username FROM Contestant WHERE Username IS NOT NULL";
rs = stmt.executeQuery(sql); //throws SQLExecption if fails
ResultSetMetaData rsmd = rs.getMetaData();
int numCols = rsmd.getColumnCount();*
// Display data, fetching until end of the result set
// Calling next moves to first or next row and returns true if success
while(rs.next() )
// Each rs after next() contains next rows data
for(final int i=1; i<=numCols; i++)
if(i > 1) System.out.print(",");
// Almost all SQL types can be cast to a string by JDBC
// System.out.print(rs.getString(i));
theList.setModel(new javax.swing.AbstractListModel() {
String[] strings = { rs.getString(i) };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return rs.getString(i); }
System.out.println("");
catch(Exception f)
titleLabel = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
// theList.setVisibleRowCount(6);
theList = new javax.swing.JList();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
titleLabel.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
titleLabel.setText("The Scrupulous Contestants!");
/* theList.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 3", "Item 4", "Item 5", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings; }
jScrollPane1.setViewportView(theList);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(70, 70, 70)
.addComponent(titleLabel))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 215, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(71, Short.MAX_VALUE))
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(titleLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(124, Short.MAX_VALUE))
pack();
}// </editor-fold>
/* private static void printResultSet(ResultSet rs) throws SQLException
DriverManager.setLogWriter(new PrintWriter(System.out) );
Connection con = DriverManager.getConnection("jdbc:mySql://localhost:3306/Contest","root","blink182");
// Get the DatabaseMetaData object to display database info
DatabaseMetaData dmd = con.getMetaData();
String sql;
Statement stmt = con.createStatement();
sql = "SELECT Username FROM Contestant WHERE Username IS NOT NULL";
rs = stmt.executeQuery(sql); //throws SQLExecption if fails
ResultSetMetaData rsmd = rs.getMetaData();
int numCols = rsmd.getColumnCount();
// Display data, fetching until end of the result set
// Calling next moves to first or next row and returns true if success
while(rs.next() )
// Each rs after next() contains next rows data
for(int i=1; i<=numCols; i++)
if(i > 1) System.out.print(",");
// Almost all SQL types can be cast to a string by JDBC
System.out.print(rs.getString(i));
System.out.println("");
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Contestantlist().setVisible(true);
// Variables declaration - do not modify
private javax.swing.JList theList;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel titleLabel;
// End of variables declaration
I can tell that im not using something correctly. Can you guys just point out how i should proceed through this? I encapsulated the piece of code that has got me confused.
Edited by: 860597 on May 29, 2011 6:29 AMpackage networks;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.PrintWriter;
import java.sql.*;
public class Contestantlist extends javax.swing.JFrame {
public Contestantlist() {
initComponents();
@SuppressWarnings("unchecked")
private void initComponents() {
try
Class.forName("org.gjt.mm.mysql.Driver");
catch (ClassNotFoundException e)
System.out.println("Unable to load driver class");
return;
try
ResultSet rs = null;
DriverManager.setLogWriter(new PrintWriter(System.out) );
Connection con = DriverManager.getConnection("jdbc:mySql://localhost:3306/Contest","root","blink182");
DatabaseMetaData dmd = con.getMetaData();
String sql;
Statement stmt = con.createStatement();
sql = "SELECT Username FROM Contestant WHERE Username IS NOT NULL";
rs = stmt.executeQuery(sql);
printResultSet(rs);
ResultSetMetaData rsmd = rs.getMetaData();
int numCols = rsmd.getColumnCount();
catch(Exception f)
titleLabel = new javax.swing.JLabel();
jScrollPane2 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
titleLabel.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
titleLabel.setText("The Scrupulous Contestants!");
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
jScrollPane2.setViewportView(jTable1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(titleLabel))
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 454, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(33, Short.MAX_VALUE))
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(titleLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(263, Short.MAX_VALUE))
pack();
}// </editor-fold>/ </editor-fold>
private static void printResultSet(ResultSet rs) throws SQLException
DriverManager.setLogWriter(new PrintWriter(System.out) );
Connection con = DriverManager.getConnection("jdbc:mySql://localhost:3306/Contest","root","blink182");
DatabaseMetaData dmd = con.getMetaData();
String sql;
Statement stmt = con.createStatement();
sql = "SELECT Username FROM Contestant WHERE Username IS NOT NULL";
rs = stmt.executeQuery(sql); //throws SQLExecption if fails
ResultSetMetaData rsmd = rs.getMetaData();
int numCols = rsmd.getColumnCount();
while(rs.next() )
for(int i=1; i<=numCols; i++)
if(i > 1) System.out.print(",");
System.out.print(rs.getString(i));
System.out.println("");
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Contestantlist().setVisible(true);
private javax.swing.JList theList;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel titleLabel;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTable jTable1;
}I have amended the code and now it does print out the specified contents of my table.
I have added a a JTable, but excuse my ignorance because i have no idea as to how to proceed from here. I can't figure out how call database entries from the array in the JTable.
Edited by: 860597 on May 29, 2011 7:27 AM -
Word 2003 to PDF conversion issue
Word 2003 and Acrobat 7, 8, and 9
Original paragarph in Word:
"After you select the user account that will host the gold image desktop virtual machine as discussed in <cross-ref>Creating User Accounts</cross-ref>, log in as that user. Next, use the win4-install-win5, win4-install-win7, or the win4-install-linux command to install a Windows 2000/XP, Windows 7, or Linux virtual machine, respectively, as discussed in this section."
Same paragraph in PDF:
After you select the user account that will host the gold image desktop virtual machine as discussed in
<cross-ref>Upgrading VERDE Server Software<cross-ref>
To upgrade VERDE server software, use the same procedure to download and install the package as
discussed in<cross-ref> Installing the VERDE Software Package</cross-ref>.
Creating User Accounts, log in as that user. Next, use the win4-install-win5, win4-install-win7,
or the win4-install-linux command to install a Windows 2000/XP, Windows 7, or Linux virtual
machine, respectively, as discussed in this section."
I cannot figure out how and why this is happening. Any ideas?What I'm talking about is how the paragraph *completely changed* for no reason. It's happening in more than one place.
Another example:
Word document (all bullets are cross-references):
See one of the following sections for more information:
§ Basic Networking
§ NAT Networking
§ Bridged Networking
§ Firewall Considerations
IMPORTANT: Do not modify any networking parameters in the virtual machine. Doing so can disable network access and guest-to-host or host-to-guest integration services."
PDF:
"See one of the following sections for more information:
Basic Networking
NAT Networking
IMPORTANT: Do not modify any networking parameters in the virtual machine. Doing so can
disable network access and guest-to-host or host-to-guest integration services.
Bridged Networking
Firewall Considerations
IMPORTANT: Do not modify any networking parameters in the virtual machine. Doing so can disable
network access and guest-to-host or host-to-guest integration services."
I tried turning cross-reference links off in the PDF, no good. Other suggestions? -
Upgrade: more Ram or SSD ?
I am using a Mac mini 2009 with 2 GB Ram Mac OS 10.5.8
It looks like there are two options to upgrade my Mac.
1. upgrade the Ram from 2 GB to 4 GB
2. replace the internal hard drive with SSD
I just want to improve the overall performance.
Which one would you recommend?
Thank you.Of course, the ultimate prize would be to upgrade both, but for overall performance, go SSD.
The difference is so noticeable and rewarding.
I had an early 2008 MB Pro 15" which I'd used a Cardbus SSD in the Expresscard slot for over a year. Now I have a current model MB Pro 15" which I do love, but in many respects it's no faster than my old one with the SSD.
If you are planning to do a lot of video editing and transcoding, image editing, etc. then the SSD has less noticeable improvement and is better served by better CPU and more RAM. But if you're consuming content, using social networking, importing and managing lots of files, databases, etc. then SSD it is. Reboots, launching multiple applications, Cmd+Tab(bing) between apps are all accelerated greatly by SSD.
An interesting idea, I've seen positive reacting to the new hybrid drives form Seagate which combine SSD with traditional HD storage. This way you still get 500GB but also, SSD and lower cost. In fact, then you could buy the RAM too! -
Modify the TicTacToeServer /client from deitel How to program
We've been given example code from the deitel & deitel book how to program and have to carry out the following alterations:
a) Modify the TicTacToeServer class to test for a win, loss or draw on each move in the game. Send a message to each client applet that indicates the result of the game when the game is over.
b) Modify the TicTacToeClient class to display a button that when clicked allows the client to play another game. The button should be enabled only when a game completes. Note that both class TicTacToeClient and class TicTacToeServer must be modified to reset the board and all state information. Also, the other TicTacToeClient should be notified that a new game is about to begin so its board and state can be reset.
c) Modify the TicTacToeClient class to provide a button that allows a client to terminate the program at any time. When the user clicks the button, the server and the other client should be notified. The server should then wait for a connection from another client so a new game can begin.
d) Modify the TicTacToeClient class and the TicTacToeServer class so the winner of a game can choose game piece X or O for the next game. Remember: X always goes first.
So far I have only been able to do part a) of the exercise im having a lot of difficulty with part b) which allows the client to play a new game.The code ive done so far is listed below if anyone can help i would be forever greatful. Thanks
// Fig. 18.9: TicTacToeClient.java
// Client that let a user play Tic-Tac-Toe with another across a network.
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import javax.swing.*;
public class TicTacToeClient extends JApplet implements Runnable, ActionListener {
private JButton Button;
private JTextField idField;
private JTextArea displayArea;
private JPanel boardPanel, panel2;
private Square board[][], currentSquare;
private Socket connection;
private DataInputStream input;
private DataOutputStream output;
private char myMark;
private boolean myTurn;
private final char X_MARK = 'X', O_MARK = 'O';
boolean done=false;
Container container;
// Set up user-interface and board
public void init()
container = getContentPane();
// set up JTextArea to display messages to user
displayArea = new JTextArea( 4, 30 );
displayArea.setEditable( false );
container.add( new JScrollPane( displayArea ), BorderLayout.SOUTH );
// set up panel for squares in board
boardPanel = new JPanel();
boardPanel.setLayout( new GridLayout( 3, 3, 0, 0 ) );
// create board
board = new Square[ 3 ][ 3 ];
// When creating a Square, the location argument to the constructor
// is a value from 0 to 8 indicating the position of the Square on
// the board. Values 0, 1, and 2 are the first row, values 3, 4,
// and 5 are the second row. Values 6, 7, and 8 are the third row.
for ( int row = 0; row < board.length; row++ ) {
for ( int column = 0; column < board[ row ].length; column++ ) {
// create Square
board[ row ][ column ] = new Square( ' ', row * 3 + column );
boardPanel.add( board[ row ][ column ] );
// textfield to display player's mark
idField = new JTextField();
idField.setEditable( false );
container.add( idField, BorderLayout.NORTH );
Button = new JButton("New Game");
container.add(Button, BorderLayout.BEFORE_FIRST_LINE);
// set up panel to contain boardPanel (for layout purposes)
panel2 = new JPanel();
panel2.add( boardPanel, BorderLayout.CENTER );
container.add( panel2, BorderLayout.CENTER );
} // end method init
// Make connection to server and get associated streams.
// Start separate thread to allow this applet to
// continually update its output in textarea display.
public void start()
// connect to server, get streams and start outputThread
try {
// make connection
connection = new Socket( getCodeBase().getHost(), 12345 );
// get streams
input = new DataInputStream( connection.getInputStream() );
output = new DataOutputStream( connection.getOutputStream() );
// catch problems setting up connection and streams
catch ( IOException ioException ) {
ioException.printStackTrace();
// create and start output thread
Thread outputThread = new Thread( this );
outputThread.start();
} // end method start
// control thread that allows continuous update of displayArea
public void run()
// get player's mark (X or O)
try {
myMark = input.readChar();
// display player ID in event-dispatch thread
SwingUtilities.invokeLater(
new Runnable() {
public void run()
idField.setText( "You are player \"" + myMark + "\"" );
myTurn = ( myMark == X_MARK ? true : false );
// receive messages sent to client and output them
while ( !done) {
processMessage( input.readUTF() );
} // end try
// process problems communicating with server
catch ( IOException ioException ) {
ioException.printStackTrace();
} // end method run
// process messages received by client
private void processMessage( String message )
// valid move occurred
if ( message.equals( "Valid move." ) ) {
displayMessage( "Valid move, please wait.\n" );
setMark( currentSquare, myMark );
// invalid move occurred
else if ( message.equals( "Invalid move, try again" ) ) {
displayMessage( message + "\n" );
myTurn = true;
// opponent moved
else if ( message.equals( "Opponent moved" ) ) {
// get move location and update board
try {
int location = input.readInt();
int row = location / 3;
int column = location % 3;
setMark( board[ row ][ column ],
( myMark == X_MARK ? O_MARK : X_MARK ) );
displayMessage( "Opponent moved. Your turn.\n" );
myTurn = true;
} // end try
// process problems communicating with server
catch ( IOException ioException ) {
ioException.printStackTrace();
} // end else if
else if ( message.equals("Game Over") ){
displayMessage("fuck sake" );
// simply display message
else
displayMessage( message + "\n" );
} // end method processMessage
// utility method called from other threads to manipulate
// outputArea in the event-dispatch thread
private void displayMessage( final String messageToDisplay )
// display message from event-dispatch thread of execution
SwingUtilities.invokeLater(
new Runnable() { // inner class to ensure GUI updates properly
public void run() // updates displayArea
displayArea.append( messageToDisplay );
displayArea.setCaretPosition(
displayArea.getText().length() );
} // end inner class
); // end call to SwingUtilities.invokeLater
// utility method to set mark on board in event-dispatch thread
private void setMark( final Square squareToMark, final char mark )
SwingUtilities.invokeLater(
new Runnable() {
public void run()
squareToMark.setMark( mark );
// send message to server indicating clicked square
public void sendClickedSquare( int location )
if ( myTurn ) {
// send location to server
try {
output.writeInt( location );
myTurn = false;
// process problems communicating with server
catch ( IOException ioException ) {
ioException.printStackTrace();
// set current Square
public void setCurrentSquare( Square square )
currentSquare = square;
public void actionPerformed(ActionEvent e) {
// I need code here
// private inner class for the squares on the board
private class Square extends JPanel {
private char mark;
private int location;
public Square( char squareMark, int squareLocation )
mark = squareMark;
location = squareLocation;
addMouseListener(
new MouseAdapter() {
public void mouseReleased( MouseEvent e )
setCurrentSquare( Square.this );
sendClickedSquare( getSquareLocation() );
} // end Square constructor
// return preferred size of Square
public Dimension getPreferredSize()
return new Dimension( 30, 30 );
// return minimum size of Square
public Dimension getMinimumSize()
return getPreferredSize();
// set mark for Square
public void setMark( char newMark )
mark = newMark;
repaint();
// return Square location
public int getSquareLocation()
return location;
// draw Square
public void paintComponent( Graphics g )
super.paintComponent( g );
g.drawRect( 0, 0, 29, 29 );
g.drawString( String.valueOf( mark ), 11, 20 );
} // end inner-class Square
} // end class TicTacToeClient
// Fig. 18.8: TicTacToeServer.java
// This class maintains a game of Tic-Tac-Toe for two client applets.
import java.awt.*;
import java.net.*;
import java.io.*;
import javax.swing.*;
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';
int moves=0;
// set up tic-tac-toe server and GUI that displays messages
public TicTacToeServer()
super( "Tic-Tac-Toe Server" );
board = new char[ 9 ];
for (int i = 0; i<9; i++){
board[i] = ' ';
players = new Player[ 2 ];
currentPlayer = PLAYER_X;
// set up ServerSocket
try {
server = new ServerSocket( 12345, 2 );
// process problems creating ServerSocket
catch( IOException ioException ) {
ioException.printStackTrace();
System.exit( 1 );
// set up JTextArea to display messages during execution
outputArea = new JTextArea();
getContentPane().add( outputArea, BorderLayout.CENTER );
outputArea.setText( "Server awaiting connections\n" );
setSize( 300, 300 );
setVisible( true );
} // end TicTacToeServer constructor
// wait for two connections so game can be played
public void execute()
// wait for each client to connect
for ( int i = 0; i < players.length; i++ ) {
// wait for connection, create Player, start thread
try {
players[ i ] = new Player( server.accept(), i );
players[ i ].start();
// process problems receiving connection from client
catch( IOException ioException ) {
ioException.printStackTrace();
System.exit( 1 );
// Player X is suspended until Player O connects.
// Resume player X now.
synchronized ( players[ PLAYER_X ] ) {
players[ PLAYER_X ].setSuspended( false );
players[ PLAYER_X ].notify();
} // end method execute
// utility method called from other threads to manipulate
// outputArea in the event-dispatch thread
private void displayMessage( final String messageToDisplay )
// display message from event-dispatch thread of execution
SwingUtilities.invokeLater(
new Runnable() { // inner class to ensure GUI updates properly
public void run() // updates outputArea
outputArea.append( messageToDisplay );
outputArea.setCaretPosition(
outputArea.getText().length() );
} // end inner class
); // end call to SwingUtilities.invokeLater
// Determine if a move is valid. This method is synchronized because
// only one move can be made at a time.
public synchronized boolean validateAndMove( int location, int player )
boolean moveDone = false;
// while not current player, must wait for turn
while ( player != currentPlayer ) {
// wait for turn
try {
wait();
// catch wait interruptions
catch( InterruptedException interruptedException ) {
interruptedException.printStackTrace();
// if location not occupied, make move
if ( !isOccupied( location ) ) {
// set move in board array
board[ location ] = currentPlayer == PLAYER_X ? X_MARK : O_MARK;
// change current player
currentPlayer = ( currentPlayer + 1 ) % 2;
// let new current player know that move occurred
players[ currentPlayer ].otherPlayerMoved( location );
notify(); // tell waiting player to continue
// tell player that made move that the move was valid
return true;
// tell player that made move that the move was not valid
else
return false;
} // end method validateAndMove
// determine whether location is occupied
public boolean isOccupied( int location )
if ( board[ location ] == X_MARK || board [ location ] == O_MARK )
return true;
else
return false;
void gameOverCheck() {
boolean over = false;
// Check rows
for (int start=0; start < 9; start += 3)
over = over || ((board[start] != ' ') &&
(board[start] == board[start+1]) &&
(board[start] == board[start+2]));
// Check columns
for (int start=0; start < 3; start++)
over = over || ((board[start] != ' ') &&
(board[start] == board[start+3]) &&
(board[start] == board[start+6]));
// Check diagonals
over = over || ((board[0] != ' ') &&
(board[0] == board[4]) && (board[0] == board[8]));
over = over || ((board[2] != ' ') &&
(board[2] == board[4]) && (board[2] == board[6]));
if (over || (moves>=9))
for ( int i = 0; i < players.length; i++ )
players.gameOver(over ? (currentPlayer+1)%2 : -1 );
public static void main( String args[] )
TicTacToeServer application = new TicTacToeServer();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
application.execute();
// private inner class Player manages each Player as a thread
private class Player extends Thread {
private Socket connection;
private DataInputStream input;
private DataOutputStream output;
private int playerNumber;
private char mark;
protected boolean suspended = true;
boolean done = false;
// set up Player thread
public Player( Socket socket, int number )
playerNumber = number;
// specify player's mark
mark = ( playerNumber == PLAYER_X ? X_MARK : O_MARK );
connection = socket;
// obtain streams from Socket
try {
input = new DataInputStream( connection.getInputStream() );
output = new DataOutputStream( connection.getOutputStream() );
// process problems getting streams
catch( IOException ioException ) {
ioException.printStackTrace();
System.exit( 1 );
} // end Player constructor
// send message that other player moved
public void otherPlayerMoved( int location )
// send message indicating move
try {
output.writeUTF( "Opponent moved" );
output.writeInt( location );
// process problems sending message
catch ( IOException ioException ) {
ioException.printStackTrace();
void gameOver(int winner) {
try {
output.writeUTF( "Game Over. " +
(( winner == -1 ) ? "No winner." :
( "Winner is " + ( winner == 0 ? 'X' : 'O' ) + "." ) ) );
done=true;
output.writeUTF("Game Over");
} catch( IOException e ) {
e.printStackTrace(); System.exit( 1 );
public void run()
// send client message indicating its mark (X or O),
// process messages from client
try {
displayMessage( "Player " + ( playerNumber ==
PLAYER_X ? X_MARK : O_MARK ) + " connected\n" );
output.writeChar( mark ); // send player's mark
// send message indicating connection
output.writeUTF( "Player " + ( playerNumber == PLAYER_X ?
"X connected\n" : "O connected, please wait\n" ) );
// if player X, wait for another player to arrive
if ( mark == X_MARK ) {
output.writeUTF( "Waiting for another player" );
// wait for player O
try {
synchronized( this ) {
while ( suspended )
wait();
// process interruptions while waiting
catch ( InterruptedException exception ) {
exception.printStackTrace();
// send message that other player connected and
// player X can make a move
output.writeUTF( "Other player connected. Your move." );
while ( ! done ) {
// get move location from client
int location = input.readInt();
// check for valid move
if ( validateAndMove( location, playerNumber ) ) {
displayMessage( "\nlocation: " + location );
output.writeUTF( "Valid move." );
gameOverCheck();
else
output.writeUTF( "Invalid move, try again" );
// close connection to client
} // end try
// process problems communicating with client
catch( IOException ioException ) {
ioException.printStackTrace();
System.exit( 1 );
// end method run
// set whether or not thread is suspended
public void setSuspended( boolean status )
suspended = status;
} // end class Player
} // end class TicTacToeServerreply #1:
http://forum.java.sun.com/thread.jspa?threadID=5114663
&tstart=0@Op. Don't multi/cross-post -
Hello,
Please give abap program making used of the BAPI function
to create purchase order creation using ME21N after importing the data from an external system.
Regards,
Sarath.Hi Naren
Check the below code.
report zmmb_po_upload.
data : begin of itab occurs 0,
collective_no(10) type c,
company_code(4) type c,
doc_type(4) type c,
vend_code(10) type c,
purch_org(4) type c,
purch_grp(3) type c,
currency(3) type c,
wo_date(10) type c,
line_item(5) type c,
itemtext(40) type c,
plant(4) type c,
matgroup(10) type c,
taxcode(2) type c,
itemcat(1) type c,
actasgntcat(1) type c,
deldate(10) type c,
glaccount(10) type c,
internalorder(12) type c,
network(12) type c,
activity(4) type c,
serlineitem(5) type c,
serviuceno(18) type c,
servicetext(40) type c,
quantity(17) type c,
unit(3) type c,
grossprice(17) type c,
end of itab.
*data : begin of itab occurs 0,
collective_no(10) type c,
doc_type(4) type c,
vend_code(10) type c,
purch_org(4) type c,
purch_grp(3) type c,
company_code(4) type c,
wo_date(10) type c,
line_item(5) type c,
actasgntcat(1) type c,
itemcat(1) type c,
itemtext(40) type c,
deldate(10) type c,
plant(4) type c,
matgroup(10) type c,
taxcode(2) type c,
serlineitem(5) type c,
serviuceno(18) type c,
servicedesc(40) type c,
quantity(17) type c,
unit(3) type c,
grossprice(17) type c,
glaccount(10) type c,
costcenter(10) type c,
internalorder(12) type c,
wbselement(24) type c,
conditiontype(4) type c,
amount(17) type c,
currency(3) type c,
end of itab.
data : xfile type string.
data : poheader like bapimepoheader,
poheaderx like bapimepoheaderx,
testrun like bapiflag-bapiflag value 'X',
poitem like bapimepoitem occurs 0 with header line,
poitemx like bapimepoitemx occurs 0 with header line,
poschedule like bapimeposchedule occurs 0 with header line,
poschedulex like bapimeposchedulx occurs 0 with header line,
poservices like bapiesllc occurs 0 with header line,
poaccount like bapimepoaccount occurs 0 with header line,
poaccountx like bapimepoaccountx occurs 0 with header line,
posrvact like bapiesklc occurs 0 with header line,
pocond like bapimepocondheader occurs 0 with header line,
pocondx like bapimepocondx occurs 0 with header line,
return like bapiret2 occurs 0 with header line,
po_number like bapimepoheader-po_number,
expheader like bapimepoheader,
wait like bapita-wait value 'X'.
parameter : fname like ibipparms-path obligatory.
at selection-screen on value-request for fname.
clear fname.
call function 'F4_FILENAME'
importing
file_name = fname
exceptions
others = 1.
at selection-screen.
if sy-ucomm = 'ONLI'.
xfile = fname.
clear itab. refresh itab.
call function 'GUI_UPLOAD'
exporting
filename = xfile
filetype = 'ASC'
has_field_separator = 'X'
tables
data_tab = itab.
if sy-subrc <> 0.
message e999(zm) with 'Error: Uploding file'.
endif.
endif.
start-of-selection.
data : wa_itab like itab.
data : counter(10) type n,
packno like ekpo-packno,
subpackno like bapiesllc-subpckg_no,
serial_no like bapimepoaccount-serial_no,
service_line(2) type n.
clear : poheader, poitem, poschedule, poservices, poaccount,
pocond, return, testrun, po_number, expheader, posrvact.
clear : poheaderx, poitemx, poschedulex, poaccountx, counter,
packno, subpackno, serial_no, service_line.
refresh : poitem, poschedule, poservices, poaccount, pocond,
return, posrvact.
refresh : poitemx, poschedulex, poaccountx.
sort itab by collective_no line_item serlineitem.
loop at itab.
clear wa_itab.
wa_itab = itab.
at new collective_no.
call function 'CONVERSION_EXIT_ALPHA_INPUT'
exporting
input = wa_itab-vend_code
importing
output = wa_itab-vend_code.
poheader-vendor = wa_itab-vend_code.
poheader-doc_type = wa_itab-doc_type.
poheader-purch_org = wa_itab-purch_org.
poheader-pur_group = wa_itab-purch_grp.
poheader-comp_code = wa_itab-company_code.
concatenate wa_itab-wo_date6(4) wa_itab-wo_date3(2)
wa_itab-wo_date+0(2) into wa_itab-wo_date.
poheader-doc_date = wa_itab-wo_date.
poheader-collect_no = wa_itab-collective_no.
poheader-currency = wa_itab-currency.
poheaderx-vendor = 'X'.
poheaderx-doc_type = 'X'.
poheaderx-purch_org = 'X'.
poheaderx-pur_group = 'X'.
poheaderx-comp_code = 'X'.
poheaderx-doc_date = 'X'.
poheaderx-collect_no = 'X'.
poheaderx-currency = 'X'.
endat.
at new line_item.
clear counter.
clear service_line.
counter = counter + 1.
if packno is initial.
select max( packno ) into packno from eslh.
packno = packno + 1.
subpackno = packno + 1.
else.
packno = subpackno + 1.
subpackno = packno + 1.
endif.
poitem-po_item = wa_itab-line_item.
poitem-acctasscat = wa_itab-actasgntcat.
poitem-item_cat = wa_itab-itemcat.
poitem-short_text = wa_itab-itemtext.
poitem-plant = wa_itab-plant.
poitem-matl_group = wa_itab-matgroup.
poitem-tax_code = wa_itab-taxcode.
poitem-quantity = 1.
poitem-pckg_no = packno.
append poitem. clear poitem.
poitemx-po_item = wa_itab-line_item.
poitemx-acctasscat = 'X'.
poitemx-item_cat = 'X'.
poitemx-short_text = 'X'.
poitemx-plant = 'X'.
poitemx-matl_group = 'X'.
poitemx-tax_code = 'X'.
poitemx-quantity = 'X'.
poitemx-pckg_no = 'X'.
append poitemx. clear poitemx.
poschedule-po_item = wa_itab-line_item.
poschedule-sched_line = 1.
poschedule-delivery_date = wa_itab-deldate.
poschedule-quantity = 1.
append poschedule. clear poschedule.
poschedulex-po_item = wa_itab-line_item.
poschedulex-sched_line = 1.
poschedulex-delivery_date = 'X'.
poschedulex-quantity = 'X'.
append poschedulex. clear poschedulex.
serial_no = serial_no + 1.
poaccount-po_item = wa_itab-line_item.
poaccount-serial_no = serial_no.
poaccount-serial_no = 1.
call function 'CONVERSION_EXIT_ALPHA_INPUT'
exporting
input = wa_itab-glaccount
importing
output = wa_itab-glaccount.
poaccount-gl_account = wa_itab-glaccount.
call function 'CONVERSION_EXIT_ALPHA_INPUT'
exporting
input = wa_itab-costcenter
importing
output = wa_itab-costcenter.
poaccount-costcenter = wa_itab-costcenter.
call function 'CONVERSION_EXIT_ALPHA_INPUT'
exporting
input = wa_itab-internalorder
importing
output = wa_itab-internalorder.
poaccount-orderid = wa_itab-internalorder.
call function 'CONVERSION_EXIT_ALPHA_INPUT'
exporting
input = wa_itab-network
importing
output = wa_itab-network.
poaccount-network = wa_itab-network.
call function 'CONVERSION_EXIT_NUMCV_INPUT'
exporting
input = wa_itab-activity
importing
output = wa_itab-activity.
poaccount-activity = wa_itab-activity.
append poaccount. clear poaccount.
poaccountx-po_item = wa_itab-line_item.
poaccountx-serial_no = serial_no.
poaccountx-gl_account = 'X'.
poaccountx-costcenter = 'X'.
poaccountx-orderid = 'X'.
poaccountx-network = 'X'.
poaccountx-activity = 'X'.
append poaccountx. clear poaccountx.
endat.
at new serlineitem.
if counter = 1.
poservices-pckg_no = packno.
poservices-line_no = counter.
poservices-subpckg_no = subpackno.
poservices-short_text = wa_itab-itemtext.
append poservices. clear poservices.
posrvact-pckg_no = packno.
posrvact-line_no = counter.
posrvact-percentage = 100.
posrvact-serial_no = serial_no.
posrvact-serial_no = 1.
append posrvact. clear posrvact.
endif.
counter = counter + 1.
service_line = service_line + 1.
poservices-pckg_no = subpackno.
poservices-line_no = counter.
poservices-ext_line = wa_itab-serlineitem.
if not wa_itab-serviuceno is initial.
call function 'CONVERSION_EXIT_ALPHA_INPUT'
exporting
input = wa_itab-serviuceno
importing
output = wa_itab-serviuceno.
endif.
poservices-service = wa_itab-serviuceno.
poservices-short_text = wa_itab-servicetext.
poservices-quantity = wa_itab-quantity.
poservices-base_uom = wa_itab-unit.
poservices-gr_price = wa_itab-grossprice.
append poservices. clear poservices.
posrvact-pckg_no = subpackno.
posrvact-line_no = counter.
posrvact-SERNO_LINE = service_line.
posrvact-SERNO_LINE = serial_no.
posrvact-percentage = 100.
posrvact-serial_no = serial_no.
posrvact-serial_no = 1.
append posrvact. clear posrvact.
endat.
at end of collective_no.
call function 'BAPI_PO_CREATE1'
exporting
poheader = poheader
poheaderx = poheaderx
importing
exppurchaseorder = po_number
expheader = expheader
tables
return = return
poitem = poitem
poitemx = poitemx
poschedule = poschedule
poschedulex = poschedulex
poaccount = poaccount
poaccountx = poaccountx
poservices = poservices
posrvaccessvalues = posrvact.
if not po_number is initial.
call function 'BAPI_TRANSACTION_COMMIT'
exporting
wait = wait.
endif.
write :/ wa_itab.
write :/ sy-uline.
loop at return.
write :/ return-message.
endloop.
write :/ sy-uline.
clear : poheader, poitem, poschedule, poservices, poaccount,
pocond, return, testrun, po_number, expheader,
posrvact.
clear : poheaderx, poitemx, poschedulex, poaccountx, counter,
packno, subpackno, serial_no, service_line.
refresh : poitem, poschedule, poservices, poaccount, pocond,
return, posrvact.
refresh : poitemx, poschedulex, poaccountx.
endat.
endloop.
end-of-selection.
Hope this helps !!!
Britto
Maybe you are looking for
-
Hi, I just purchased an ipod touch for my son and it had been opened so there was a discount on the phone, now it won't open because the person who had it before put a passcode on it and I can't get it to show up in itunes. How can I just restore it
-
Hi, I have a query which i need to represent in obiee. For eg:*(NOT ACTUAL QUERY)* SELECT empid,name FROM T1 WHERE NOT EXISTS (SELECT 1 FROM T2 WHERE T1.empid=T2.empid) I know this we can do it by SQL directly in the physical layer.But i want to know
-
Unable to check for available downloads.....error
The iTunes Store is temporarily unavailable. Please try again later. I'm getting the above error message when selecting "check for available downloads" in the Store menu. Problem started when I tried to download the updated to the Remote App yesterda
-
When i try to use video chat with friends (overseas) it works fine for a few minutes then always disconnects. The error message looks like this "2006-01-08 07:29:49 -0800: No data has been received for the last 10 seconds. Audio channel info: local m
-
Kernel panic, mac mini crash
Hello, I have this problem many times... My mac crash on boot, and I have this error. How can I do ? Thanks Interval Since Last Panic Report: 180765 sec Panics Since Last Report: 7 Anonymous UUID: D732853C-3D4C-406F-8A7B-