- Timestamp:
- 02/10/09 08:08:09 (13 years ago)
- Location:
- chess/src/chess
- Files:
-
- 1 added
- 9 edited
Legend:
- Unmodified
- Added
- Removed
-
chess/src/chess/MSG.properties
r28 r34 32 32 new-game.incoming-client.description = \u0412\u0445\u043e\u0434\u044f\u0449\u0435\u0435 \u0441\u043e\u0435\u0434\u0438\u043d\u0435\u043d\u0438\u0435 \u043e\u0442 {0}. \u0418\u0433\u0440\u0430\u0442\u044c \u0441 \u043d\u0438\u043c? 33 33 34 wait-for-bluetooth.title = \u041 8\u043d\u0438\u0446\u0438\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f bluetooth. \u041f\u043e\u0434\u043e\u0436\u0434\u0438\u0442\u0435...34 wait-for-bluetooth.title = \u0416\u0434\u0435\u043c \u0432\u0445\u043e\u0434\u044f\u0449\u0435\u0435 \u0441\u043e\u0435\u0434\u0438\u043d\u0435\u043d\u0438\u0435... 35 35 36 36 wait.title = \u041e\u0436\u0438\u0434\u0430\u043d\u0438\u0435... -
chess/src/chess/remote/IAsyncProcess.java
r29 r34 6 6 */ 7 7 public interface IAsyncProcess { 8 9 10 11 12 8 public static final int NOT_STARTED = -1; 9 public static final int IN_PROCESS = 0; 10 public static final int SUCCEEDED = 1; 11 public static final int FAILED = 2; 12 public static final int INTERRUPTED = 3; 13 13 14 14 public int status(); 15 15 16 16 public void stop( final int waitMillis ); 17 17 18 public IAsyncProcessListener getListener(); 18 public IAsyncProcessListener getListener(); 19 20 public Throwable getError(); 19 21 } -
chess/src/chess/remote/impl/BTRemote.java
r32 r34 20 20 */ 21 21 public class BTRemote implements IRemote { 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 if( preknownDevices != null ) {39 for( int i = 0; i < preknownDevices.length; i++ ) {40 41 42 43 44 45 if( cachedDevices != null ) {46 for( int i = 0; i < cachedDevices.length; i++ ) {47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 22 public static final String BTSPP_SCHEME = "btspp://"; 23 public static final String MY_SERVICE_NUMBER = "3B9FA89520078C303355AAA694238F08;name=ChessGameServer"; 24 25 public static final IRemoteNode[] EMPTY = new IRemoteNode[0]; 26 27 private final LocalDevice localDevice; 28 private final Vector devices = new Vector(); 29 30 public BTRemote() throws Exception { 31 localDevice = LocalDevice.getLocalDevice(); 32 fillupCache(); 33 } 34 35 private synchronized void fillupCache() { 36 final DiscoveryAgent agent = localDevice.getDiscoveryAgent(); 37 final RemoteDevice[] preknownDevices = agent.retrieveDevices( DiscoveryAgent.PREKNOWN ); 38 if ( preknownDevices != null ) { 39 for ( int i = 0; i < preknownDevices.length; i++ ) { 40 final RemoteDevice device = preknownDevices[i]; 41 devices.addElement( device ); 42 } 43 } 44 final RemoteDevice[] cachedDevices = agent.retrieveDevices( DiscoveryAgent.CACHED ); 45 if ( cachedDevices != null ) { 46 for ( int i = 0; i < cachedDevices.length; i++ ) { 47 final RemoteDevice device = cachedDevices[i]; 48 devices.addElement( device ); 49 } 50 } 51 } 52 53 private synchronized void refreshCache() { 54 devices.removeAllElements(); 55 fillupCache(); 56 } 57 58 public IAsyncProcess waitForIncoming( final IServerListener l ) { 59 return new WaitForIncomingThread( localDevice, l ); 60 } 61 62 public IAsyncProcess getAvailable( final boolean refresh, 63 final IClientListener listener ) { 64 final DiscoveryAgent agent = localDevice.getDiscoveryAgent(); 65 return new QueryDeviceProcess( this, refresh, agent, listener ); 66 66 // try { 67 67 // } catch( Exception e ) { … … 76 76 // return null; 77 77 // } 78 } 79 80 private synchronized IRemoteNode[] getNodes() { 81 if( devices.isEmpty() ) { 82 return EMPTY; 83 } 84 final int length = devices.size(); 85 final IRemoteNode[] nodes = new IRemoteNode[length]; 86 for( int i = 0; i < length; i++ ) { 87 try { 88 final RemoteDevice device = ( RemoteDevice ) devices.elementAt( i ); 89 final BTNode node = new BTNode( device ); 90 nodes[i] = node; 91 } catch( IOException e ) { 92 //todo remove node from list, or causing NPE 93 e.printStackTrace(); 94 } 95 } 96 return nodes; 97 } 98 99 private static class WaitForIncomingThread extends BaseAsyncProcess { 100 private final LocalDevice localDevice; 101 private StreamConnectionNotifier server; 102 103 public WaitForIncomingThread( final LocalDevice local, 104 final IServerListener listener ) { 105 super( listener ); 106 this.localDevice = local; 107 start(); 108 } 109 110 public void run() { 111 try { 112 localDevice.setDiscoverable( DiscoveryAgent.GIAC ); 113 setStatus( IN_PROCESS ); 114 while( true ) { 115 server = ( StreamConnectionNotifier ) Connector.open( 116 BTSPP_SCHEME + "localhost:" + MY_SERVICE_NUMBER, 117 Connector.READ_WRITE, 118 true 119 ); 120 Util.log.println( "creating server and waiting for incoming" ); 121 try { 122 final IServerListener _listener = ( IServerListener ) listener; 123 while( true ) { 124 // Îæèäàåì âõîäÿùåå ïîòîêîâîå ñîåäèíåíèå 125 final StreamConnection conn = server.acceptAndOpen(); 126 Util.log.println( "accepted incoming: " + conn ); 127 final BTNode client = new BTNode( conn ); 128 if( _listener.incoming( client ) ) { 129 //åñëè êëèåíò ïðèíÿò -- âûõîäèì (èãðà äîïóñêàåò òîëüêî îäíîãî ñîïåðíèêà) 130 Util.log.println( "client accepted -> close server" ); 131 setStatus( SUCCEEDED ); 132 return; 133 } 134 client.close( true ); 135 } 136 } catch( InterruptedIOException ex ) { 137 setStatus( INTERRUPTED ); 138 Util.log.println( "server was closed: " + ex.getMessage() ); 139 return; 140 } catch( IOException ex ) { 141 Util.log.println( "server got error -- trying to recreate server connection" ); 142 ex.printStackTrace(); 143 } finally { 144 if( server != null ) { 145 try { 146 server.close(); 147 server = null; 148 } catch( IOException e ) { 149 e.printStackTrace(); 150 } 151 } 152 } 153 } 154 } catch( IOException ex ) { 155 //åñëè íå óäàëîñü îòêðûòü ñîåäèíåíèå -- ýòî ïèçäåö. óõîäèì 156 //...íå óäàëîñü îïóáëèêîâàòü óñòðîéñòâî -- ïèçäåö, óõîäèì 157 ex.printStackTrace(); 158 setStatus( FAILED ); 159 } finally { 160 listener.finished( null ); 161 Util.log.println( "server stopped" ); 162 } 163 } 164 165 public void stop( final int waitMillis ) { 166 if( isAlive() ) { 167 if( server != null ) { 168 try { 169 server.close(); 170 server = null; 171 } catch( IOException e ) { 172 e.printStackTrace(); 173 } 174 } 175 waitForThread( waitMillis ); 176 } 177 } 178 179 } 180 181 private static class QueryDeviceProcess extends BaseAsyncProcess implements DiscoveryListener { 182 private final BTRemote remote; 183 private final boolean realQuery; 184 private final DiscoveryAgent agent; 185 186 public QueryDeviceProcess( final BTRemote remote, 187 final boolean realQuery, 188 final DiscoveryAgent agent, 189 final IClientListener listener ) { 190 super( listener ); 191 this.remote = remote; 192 this.agent = agent; 193 this.realQuery = realQuery; 194 start(); 195 } 196 197 public void run() { 198 199 setStatus( IN_PROCESS ); 200 Util.log.println( "starting query device list" ); 201 try { 202 /** 203 * Íåïîíÿòíî, ÿâëÿåòñÿ ëè ýòîò çàïðîñ ñèíõðîííûì, èëè àñèíõðîííûì -- 204 * äîêóìåíòàöèÿ íà ýòîò ñ÷åò ìîë÷èò, à ïðàêòèêà ïîêàçûâàåò, ÷òî 205 * áûâàåò è òàê è ýäàê. Ïîýòîìó ñòðàõóåìñÿ íà âñÿêèé ñëó÷àé îò 206 * íåâåäîìîé õóéíè è äåëàåì ýòî â îòäåëüíîì ïîòîêå 207 */ 208 if( realQuery ) { 209 agent.startInquiry( DiscoveryAgent.GIAC, this ); 210 } else { 211 listener.finished( remote.getNodes() ); 212 } 213 } catch( BluetoothStateException e ) { 214 e.printStackTrace(); 215 setStatus( FAILED ); 216 listener.finished( null ); 217 } 218 } 219 220 221 public void stop( final int waitMillis ) { 222 if( status() == IN_PROCESS ) { 223 if( realQuery ) { 224 agent.cancelInquiry( this ); 225 } else { 226 interrupt(); 227 } 228 waitForThread( waitMillis ); 229 } 230 } 231 232 public void deviceDiscovered( final RemoteDevice btDevice, 233 final DeviceClass cod ) { 234 Util.log.println( "device found:" + btDevice.getBluetoothAddress() ); 235 } 236 237 public void servicesDiscovered( final int transID, 238 final ServiceRecord[] servRecord ) { 239 Util.log.println( "service found:" + transID ); 240 } 241 242 public void serviceSearchCompleted( final int transID, 243 final int respCode ) { 244 245 } 246 247 public void inquiryCompleted( final int discType ) { 248 switch( discType ) { 249 case INQUIRY_COMPLETED: 250 Util.log.println( "device list query finished" ); 251 remote.refreshCache(); 252 setStatus( SUCCEEDED ); 253 listener.finished( remote.getNodes() ); 254 break; 255 case INQUIRY_TERMINATED: 256 Util.log.println( "device list query interrupted" ); 257 setStatus( INTERRUPTED ); 258 listener.finished( null ); 259 break; 260 case INQUIRY_ERROR: 261 Util.log.println( "device list query failed" ); 262 setStatus( FAILED ); 263 listener.finished( null ); 264 break; 265 } 266 } 267 } 78 } 79 80 private synchronized IRemoteNode[] getNodes() { 81 if ( devices.isEmpty() ) { 82 return EMPTY; 83 } 84 final int length = devices.size(); 85 final IRemoteNode[] nodes = new IRemoteNode[devices.size()]; 86 boolean wasFailed = false; 87 for ( int i = 0; i < length; i++ ) { 88 try { 89 final RemoteDevice device = ( RemoteDevice )devices.elementAt( i ); 90 final BTNode node = new BTNode( device ); 91 nodes[i] = node; 92 } catch ( IOException e ) { 93 wasFailed = true; 94 e.printStackTrace(); 95 } 96 } 97 if ( wasFailed ) { 98 //óäàëÿåì ïóñòûå ÿ÷åéêè 99 final Vector res = new Vector( nodes.length ); 100 for ( int i = 0; i < nodes.length; i++ ) { 101 final IRemoteNode node = nodes[i]; 102 if ( node != null ) { 103 res.addElement( node ); 104 } 105 } 106 107 final IRemoteNode[] _nodes = new IRemoteNode[res.size()]; 108 res.copyInto( _nodes ); 109 return _nodes; 110 } else { 111 return nodes; 112 } 113 } 114 115 private static class WaitForIncomingThread extends BaseAsyncProcess { 116 private final LocalDevice localDevice; 117 private StreamConnectionNotifier server; 118 119 public WaitForIncomingThread( final LocalDevice local, 120 final IServerListener listener ) { 121 super( listener ); 122 this.localDevice = local; 123 start(); 124 } 125 126 public void run() { 127 try { 128 localDevice.setDiscoverable( DiscoveryAgent.GIAC ); 129 setStatus( IN_PROCESS ); 130 while ( true ) { 131 server = ( StreamConnectionNotifier )Connector.open( 132 BTSPP_SCHEME + "localhost:" + MY_SERVICE_NUMBER, 133 Connector.READ_WRITE, 134 true 135 ); 136 Util.log.println( "creating server and waiting for incoming" ); 137 try { 138 final IServerListener _listener = ( IServerListener )listener; 139 while ( server != null ) { 140 // Îæèäàåì âõîäÿùåå ïîòîêîâîå ñîåäèíåíèå 141 final StreamConnection conn = server.acceptAndOpen(); 142 Util.log.println( "accepted incoming: " + conn ); 143 final BTNode client = new BTNode( conn ); 144 if ( _listener.incoming( client ) ) { 145 //åñëè êëèåíò ïðèíÿò -- âûõîäèì (èãðà äîïóñêàåò òîëüêî îäíîãî ñîïåðíèêà) 146 Util.log.println( "client accepted -> close server" ); 147 setStatus( SUCCEEDED ); 148 return; 149 } 150 client.close( true ); 151 } 152 } catch ( InterruptedIOException ex ) { 153 //setStatus( INTERRUPTED ); 154 //return; 155 throw ex; 156 } catch ( IOException ex ) { 157 Util.log.println( "server got error -- trying to recreate server connection" ); 158 ex.printStackTrace(); 159 } finally { 160 if ( server != null ) { 161 try { 162 server.close(); 163 server = null; 164 } catch ( IOException e ) { 165 e.printStackTrace(); 166 } 167 } 168 } 169 } 170 } catch ( Throwable ex ) { 171 //åñëè íå óäàëîñü îòêðûòü ñîåäèíåíèå -- ýòî ïèçäåö. óõîäèì 172 //...íå óäàëîñü îïóáëèêîâàòü óñòðîéñòâî -- ïèçäåö, óõîäèì 173 if ( isQueryInterrupt() ) { 174 Util.log.println( "server was closed: " + ex.getMessage() ); 175 setStatus( INTERRUPTED ); 176 } else { 177 setStatus( FAILED, ex ); 178 } 179 } finally { 180 listener.finished( null ); 181 Util.log.println( "server stopped" ); 182 } 183 } 184 185 public void stop( final int waitMillis ) { 186 setQueryInterrupt(); 187 if ( isAlive() ) { 188 if ( server != null ) { 189 try { 190 server.close(); 191 server = null; 192 } catch ( IOException e ) { 193 e.printStackTrace(); 194 } 195 } 196 waitForThread( waitMillis ); 197 } 198 } 199 200 } 201 202 private static class QueryDeviceProcess extends BaseAsyncProcess implements DiscoveryListener { 203 private final BTRemote remote; 204 private final boolean realQuery; 205 private final DiscoveryAgent agent; 206 207 public QueryDeviceProcess( final BTRemote remote, 208 final boolean realQuery, 209 final DiscoveryAgent agent, 210 final IClientListener listener ) { 211 super( listener ); 212 this.remote = remote; 213 this.agent = agent; 214 this.realQuery = realQuery; 215 start(); 216 } 217 218 public void run() { 219 setStatus( IN_PROCESS ); 220 221 Util.log.println( "starting query device list" ); 222 try { 223 /** 224 * Íåïîíÿòíî, ÿâëÿåòñÿ ëè ýòîò çàïðîñ ñèíõðîííûì, èëè àñèíõðîííûì -- 225 * äîêóìåíòàöèÿ íà ýòîò ñ÷åò ìîë÷èò, à ïðàêòèêà ïîêàçûâàåò, ÷òî 226 * áûâàåò è òàê è ýäàê. Ïîýòîìó ñòðàõóåìñÿ îò íåâåäîìîé õóéíè è 227 * äåëàåì ýòî â îòäåëüíîì ïîòîêå 228 */ 229 if ( realQuery ) { 230 agent.startInquiry( DiscoveryAgent.GIAC, this ); 231 } else { 232 final IRemoteNode[] nodes = remote.getNodes(); 233 setStatus( SUCCEEDED ); 234 listener.finished( nodes ); 235 } 236 } catch ( Throwable e ) { 237 if ( isQueryInterrupt() ) { 238 setStatus( INTERRUPTED ); 239 } else { 240 setStatus( FAILED, e ); 241 } 242 listener.finished( null ); 243 } 244 } 245 246 247 public void stop( final int waitMillis ) { 248 setQueryInterrupt(); 249 if ( status() == IN_PROCESS ) { 250 if ( realQuery ) { 251 agent.cancelInquiry( this ); 252 } else { 253 interrupt(); 254 } 255 waitForThread( waitMillis ); 256 } 257 } 258 259 public void deviceDiscovered( final RemoteDevice btDevice, 260 final DeviceClass cod ) { 261 Util.log.println( "device found:" + btDevice.getBluetoothAddress() ); 262 } 263 264 public void servicesDiscovered( final int transID, 265 final ServiceRecord[] servRecord ) { 266 //Util.log.println( "service found:" + transID ); 267 } 268 269 public void serviceSearchCompleted( final int transID, 270 final int respCode ) { 271 272 } 273 274 public void inquiryCompleted( final int discType ) { 275 switch ( discType ) { 276 case INQUIRY_COMPLETED: 277 Util.log.println( "device list query finished" ); 278 remote.refreshCache(); 279 setStatus( SUCCEEDED ); 280 listener.finished( remote.getNodes() ); 281 break; 282 case INQUIRY_TERMINATED: 283 Util.log.println( "device list query interrupted" ); 284 setStatus( INTERRUPTED ); 285 listener.finished( null ); 286 break; 287 case INQUIRY_ERROR: 288 Util.log.println( "device list query failed" ); 289 setStatus( FAILED ); 290 listener.finished( null ); 291 break; 292 default: 293 throw new IllegalStateException( "Unknown type:" + discType ); 294 } 295 } 296 } 268 297 } -
chess/src/chess/remote/impl/BaseAsyncProcess.java
r29 r34 12 12 */ 13 13 public class BaseAsyncProcess extends Thread implements IAsyncProcess { 14 14 protected final IAsyncProcessListener listener; 15 15 16 private int status = NOT_STARTED; 16 private int status = NOT_STARTED; 17 private Throwable lastError = null; 18 private volatile boolean queryInterrupt = false; 17 19 18 19 20 20 public BaseAsyncProcess( final IAsyncProcessListener listener ) { 21 this.listener = listener; 22 } 21 23 22 23 24 24 public final int status() { 25 return status; 26 } 25 27 26 protected final synchronized void setStatus( final int status ) { 27 switch( status ) { 28 case IN_PROCESS: 29 case SUCCEEDED: 30 case FAILED: 31 case INTERRUPTED: 32 this.status = status; 33 break; 34 default: 35 throw new IllegalArgumentException( "Status " + status + " is unknown" ); 36 } 37 } 28 protected synchronized final boolean isQueryInterrupt() { 29 return queryInterrupt; 30 } 38 31 39 public void stop( final int waitMillis ) { 40 if( isAlive() ) { 41 interrupt(); 42 waitForThread( waitMillis ); 43 } 44 } 32 protected synchronized void setQueryInterrupt() { 33 this.queryInterrupt = true; 34 } 45 35 46 protected void waitForThread( final int waitMillis ) { 47 if( waitMillis > 0 48 && isAlive() 49 && Thread.currentThread() != this ) { 50 Util.log.println( "waiting for thread to finish" ); 51 synchronized( this ) { 52 try { 53 wait( waitMillis ); 54 } catch( InterruptedException e ) { 55 } 56 } 57 } 58 } 36 protected final synchronized void setStatus( final int status ) { 37 setStatus( status, null ); 38 } 59 39 60 public final IAsyncProcessListener getListener() { 61 return listener; 62 } 40 protected final synchronized void setStatus( final int status, 41 final Throwable t ) { 42 switch ( status ) { 43 case IN_PROCESS: 44 case SUCCEEDED: 45 case FAILED: 46 case INTERRUPTED: 47 this.status = status; 48 break; 49 default: 50 throw new IllegalArgumentException( "Status " + status + " is unknown" ); 51 } 52 if ( t != null ) { 53 this.lastError = t; 54 t.printStackTrace(); 55 } 56 } 57 58 public void stop( final int waitMillis ) { 59 setQueryInterrupt(); 60 if ( isAlive() ) { 61 interrupt(); 62 waitForThread( waitMillis ); 63 } 64 } 65 66 protected void waitForThread( final int waitMillis ) { 67 if ( waitMillis > 0 68 && isAlive() 69 && Thread.currentThread() != this ) { 70 Util.log.println( "waiting for thread to finish" ); 71 synchronized ( this ) { 72 try { 73 wait( waitMillis ); 74 } catch ( InterruptedException e ) { 75 } 76 } 77 } 78 } 79 80 public final IAsyncProcessListener getListener() { 81 return listener; 82 } 83 84 public Throwable getError() { 85 return lastError; 86 } 63 87 } -
chess/src/chess/remote/impl/debug/DebugRemote.java
r32 r34 21 21 */ 22 22 public class DebugRemote implements IRemote { 23 private static final Timer TIMER = new Timer(); 24 25 private static final Random random = new Random(); 26 27 private final int networkLatency; 28 private final int userLatency; 29 30 public DebugRemote( final int networkLatency, 31 final int userLatency ) { 32 this.networkLatency = networkLatency; 33 this.userLatency = userLatency; 34 } 35 36 private InputStream prepareLog( final Player player ) { 37 final ByteArrayOutputStream out = new ByteArrayOutputStream(); 38 try { 39 final int yPawnLine = ( player == Player.WHITE ) ? ( 1 ) : ( 6 ); 40 final int dir = player.getDirection(); 41 putAction( player, out, 2 * userLatency, 0, yPawnLine, 0, yPawnLine + 2 * dir ); 42 43 putAction( player, out, 12 * userLatency, 3, yPawnLine, 3, yPawnLine + 2 * dir ); 44 45 putAction( player, out, 10 * userLatency, 4, yPawnLine, 4, yPawnLine + dir ); 46 47 putAction( player, out, 20 * userLatency, 4, yPawnLine + dir, 4, yPawnLine + 2 * dir ); 48 49 //new GenericDatagram( 50 // new SystemAction( 51 // SystemAction.SURRENDER, 52 // player 53 // ) 54 //).write( out ); 55 } catch( IOException e ) { 56 e.printStackTrace(); 57 } 58 59 return new ByteArrayInputStream( out.toByteArray() ); 60 } 61 62 private static void putAction( final Player player, 63 final OutputStream out, 64 final int duration, 65 final int xFrom, 66 final int yFrom, 67 final int xTo, 68 final int yTo ) throws IOException { 69 final Action a = new Action( 70 player, 71 duration, 72 xFrom, yFrom, 73 xTo, yTo 74 ); 75 new GenericDatagram( a ).write( out ); 76 final SystemAction yourTurnAction = SystemAction.yourTurn( player.opponent() ); 77 new GenericDatagram( yourTurnAction ).write( out ); 78 } 79 80 public IAsyncProcess waitForIncoming( final IServerListener l ) { 81 return new ServerAsyncProcess( l ); 82 } 83 84 public IAsyncProcess getAvailable( final boolean force, 85 final IClientListener l ) { 86 if( !force ) { 87 try { 88 Thread.sleep( networkLatency ); 89 } catch( InterruptedException e ) { 90 e.printStackTrace(); 91 } 92 l.finished( BTRemote.EMPTY ); 93 return null; 94 } else { 95 final QueryDeviceProcess process = new QueryDeviceProcess( this, l ); 96 TIMER.schedule( process, networkLatency ); 97 return process; 98 } 99 } 100 101 private class ServerAsyncProcess extends BaseAsyncProcess { 102 public ServerAsyncProcess( final IServerListener listener ) { 103 super( listener ); 104 start(); 105 } 106 107 public void run() { 108 try { 109 setStatus( IN_PROCESS ); 110 final IServerListener _listener = ( IServerListener ) listener; 111 while( true ) { 112 synchronized( this ) { 113 wait( 4 * networkLatency ); 114 } 115 if( _listener.incoming( new ClientRemoteNode() ) ) { 116 Util.log.println( "emulate incoming connection: OK" ); 117 setStatus( SUCCEEDED ); 118 return; 119 } 120 } 121 } catch( InterruptedException ex ) { 122 setStatus( INTERRUPTED ); 123 } catch( Exception ex ) { 124 setStatus( FAILED ); 125 } finally { 126 listener.finished( null ); 127 } 128 } 129 130 } 131 132 private class ClientRemoteNode implements IRemoteNode { 133 private InputStream is; 134 private IConnectionListener listener; 135 private Player player; 136 137 public String getName() { 138 return "debug client"; 139 } 140 141 public void setListener( final IConnectionListener l ) { 142 this.listener = l; 143 } 144 145 public void start() { 146 TIMER.schedule( 147 new TimerTask() { 148 public void run() { 149 listener.connected(); 150 } 151 }, 152 networkLatency 153 ); 154 } 155 156 public void send( final IDatagram data ) { 157 if( listener != null ) { 158 Util.log.println( "emulate data send: " + data ); 159 TIMER.schedule( 160 new TimerTask() { 161 public void run() { 162 Util.log.println( "emulate wasSent: " + data ); 163 listener.wasSent( data ); 164 if( data instanceof SystemAction ) { 165 final SystemAction sa = ( SystemAction ) data; 166 if( sa.type() == SystemAction.SET_PLAYER ) { 167 player = sa.getPlayer(); 168 is = prepareLog( player ); 169 } else 170 if( sa.type() == SystemAction.YOUR_TURN ) { 171 try { 172 if( is.available() > 0 ) { 173 final GenericDatagram aPacket = new GenericDatagram( ClientRemoteNode.this.is ); 174 final GenericDatagram saPacket = new GenericDatagram( ClientRemoteNode.this.is ); 175 Thread.sleep( 5 * networkLatency ); 176 TIMER.schedule( 177 new TimerTask() { 178 public void run() { 179 Util.log.println( "recv: emulate" ); 180 181 Util.log.println( "recv: " + aPacket.wrapped() ); 182 listener.received( aPacket.wrapped() ); 183 184 Util.log.println( "recv: " + saPacket.wrapped() ); 185 listener.received( saPacket.wrapped() ); 186 } 187 }, 188 ( ( Action ) aPacket.wrapped() ).duration() 189 ); 190 } else { 191 listener.received( SystemAction.surrender( player ) ); 192 } 193 } catch( Exception e ) { 194 e.printStackTrace(); 195 } 196 } 197 } 198 } 199 }, 200 2 * networkLatency 201 ); 202 } 203 } 204 205 public void close( final boolean safe ) { 206 listener.closed(); 207 } 23 private static final Timer TIMER = new Timer(); 24 25 private static final Random random = new Random(); 26 27 private final int networkLatency; 28 private final int userLatency; 29 30 public DebugRemote( final int networkLatency, 31 final int userLatency ) { 32 this.networkLatency = networkLatency; 33 this.userLatency = userLatency; 34 } 35 36 private InputStream prepareLog( final Player player ) { 37 final ByteArrayOutputStream out = new ByteArrayOutputStream(); 38 try { 39 final int yPawnLine = ( player == Player.WHITE ) ? ( 1 ) : ( 6 ); 40 final int dir = player.getDirection(); 41 putAction( player, out, 2 * userLatency, 0, yPawnLine, 0, yPawnLine + 2 * dir ); 42 43 putAction( player, out, 12 * userLatency, 3, yPawnLine, 3, yPawnLine + 2 * dir ); 44 45 putAction( player, out, 10 * userLatency, 4, yPawnLine, 4, yPawnLine + dir ); 46 47 putAction( player, out, 20 * userLatency, 4, yPawnLine + dir, 4, yPawnLine + 2 * dir ); 48 49 //new GenericDatagram( 50 // new SystemAction( 51 // SystemAction.SURRENDER, 52 // player 53 // ) 54 //).write( out ); 55 } catch ( IOException e ) { 56 e.printStackTrace(); 57 } 58 59 return new ByteArrayInputStream( out.toByteArray() ); 60 } 61 62 private static void putAction( final Player player, 63 final OutputStream out, 64 final int duration, 65 final int xFrom, 66 final int yFrom, 67 final int xTo, 68 final int yTo ) throws IOException { 69 final Action a = new Action( 70 player, 71 duration, 72 xFrom, yFrom, 73 xTo, yTo 74 ); 75 new GenericDatagram( a ).write( out ); 76 final SystemAction yourTurnAction = SystemAction.yourTurn( player.opponent() ); 77 new GenericDatagram( yourTurnAction ).write( out ); 78 } 79 80 public IAsyncProcess waitForIncoming( final IServerListener l ) { 81 return new ServerAsyncProcess( l ); 82 } 83 84 public IAsyncProcess getAvailable( final boolean force, 85 final IClientListener l ) { 86 if ( !force ) { 87 try { 88 Thread.sleep( networkLatency ); 89 } catch ( InterruptedException e ) { 90 e.printStackTrace(); 91 } 92 l.finished( BTRemote.EMPTY ); 93 return null; 94 } else { 95 final QueryDeviceProcess process = new QueryDeviceProcess( this, l ); 96 TIMER.schedule( process, networkLatency ); 97 return process; 98 } 99 } 100 101 private class ServerAsyncProcess extends BaseAsyncProcess { 102 public ServerAsyncProcess( final IServerListener listener ) { 103 super( listener ); 104 start(); 105 } 106 107 public void run() { 108 try { 109 setStatus( IN_PROCESS ); 110 final IServerListener _listener = ( IServerListener )listener; 111 while ( true ) { 112 synchronized ( this ) { 113 wait( 4 * networkLatency ); 114 } 115 if ( _listener.incoming( new ClientRemoteNode() ) ) { 116 Util.log.println( "emulate incoming connection: OK" ); 117 setStatus( SUCCEEDED ); 118 return; 119 } 120 } 121 } catch ( InterruptedException ex ) { 122 setStatus( INTERRUPTED ); 123 } catch ( Exception ex ) { 124 setStatus( FAILED ); 125 } finally { 126 listener.finished( null ); 127 } 128 } 129 130 } 131 132 private class ClientRemoteNode implements IRemoteNode { 133 private InputStream is; 134 private IConnectionListener listener; 135 private Player player; 136 137 public String getName() { 138 return "debug client"; 139 } 140 141 public void setListener( final IConnectionListener l ) { 142 this.listener = l; 143 } 144 145 public void start() { 146 TIMER.schedule( 147 new TimerTask() { 148 public void run() { 149 listener.connected(); 150 } 151 }, 152 networkLatency 153 ); 154 } 155 156 public void send( final IDatagram data ) { 157 if ( listener != null ) { 158 Util.log.println( "emulate data send: " + data ); 159 TIMER.schedule( 160 new TimerTask() { 161 public void run() { 162 Util.log.println( "emulate wasSent: " + data ); 163 listener.wasSent( data ); 164 if ( data instanceof SystemAction ) { 165 final SystemAction sa = ( SystemAction )data; 166 if ( sa.type() == SystemAction.SET_PLAYER ) { 167 player = sa.getPlayer(); 168 is = prepareLog( player ); 169 } else if ( sa.type() == SystemAction.YOUR_TURN ) { 170 try { 171 if ( is.available() > 0 ) { 172 final GenericDatagram aPacket = new GenericDatagram( ClientRemoteNode.this.is ); 173 final GenericDatagram saPacket = new GenericDatagram( ClientRemoteNode.this.is ); 174 Thread.sleep( 5 * networkLatency ); 175 TIMER.schedule( 176 new TimerTask() { 177 public void run() { 178 Util.log.println( "recv: emulate" ); 179 180 Util.log.println( "recv: " + aPacket.wrapped() ); 181 listener.received( aPacket.wrapped() ); 182 183 Util.log.println( "recv: " + saPacket.wrapped() ); 184 listener.received( saPacket.wrapped() ); 185 } 186 }, 187 ( ( Action )aPacket.wrapped() ).duration() 188 ); 189 } else { 190 listener.received( SystemAction.surrender( player ) ); 191 } 192 } catch ( Exception e ) { 193 e.printStackTrace(); 194 } 195 } 196 } 197 } 198 }, 199 2 * networkLatency 200 ); 201 } 202 } 203 204 public void close( final boolean safe ) { 205 listener.closed(); 206 } 208 207 209 208 public Throwable getError() { … … 212 211 } 213 212 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 if( listener == null ) {235 236 237 238 239 240 241 242 243 244 245 246 247 if( player == Player.WHITE ) {248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 if( listener != null ) {272 273 274 275 276 277 278 if( data instanceof SystemAction ) {279 final SystemAction sa = ( SystemAction )data;280 if( sa.type() == SystemAction.SET_PLAYER ) {281 282 283 if( sa.type() == SystemAction.YOUR_TURN ) {284 285 286 287 288 289 290 291 292 293 294 295 296 if( is.available() > 0 ) {297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 ( ( Action )aPacket.wrapped() ).duration()313 314 315 316 317 } catch( Exception e ) {318 319 320 321 322 323 324 213 private class ServerRemoteNode implements IRemoteNode { 214 private InputStream is; 215 private IConnectionListener listener; 216 private final Player player; 217 private final String name; 218 219 private ServerRemoteNode( final int n ) { 220 player = Player.byType( n % 2 ); 221 name = "debug server #" + n + "[" + player + "]"; 222 } 223 224 public String getName() { 225 return name; 226 } 227 228 public void setListener( final IConnectionListener l ) { 229 this.listener = l; 230 } 231 232 public void start() { 233 if ( listener == null ) { 234 throw new IllegalStateException( "listener can't be null in start!" ); 235 } 236 //ïîñûëàåì íà÷àëüíóþ ïîñëåäîâàòåëüíîñòü -- 237 //restore logged actions, SET_PLAYER, YOUR_TURN 238 Util.log.println( "server emulation started: " + name ); 239 is = prepareLog( player ); 240 final TimerTask handshakeTask = new TimerTask() { 241 public void run() { 242 Util.log.println( name + ": sending SET_PLAYER" ); 243 listener.received( 244 SystemAction.setPlayer( player.opponent() ) 245 ); 246 if ( player == Player.WHITE ) { 247 packet(); 248 } else { 249 listener.received( 250 SystemAction.yourTurn( player.opponent() ) 251 ); 252 //èíà÷å æäåì YOUR_TURN îò áåëûõ 253 } 254 } 255 }; 256 257 TIMER.schedule( 258 new TimerTask() { 259 public void run() { 260 Util.log.println( name + ":sending connect" ); 261 listener.connected(); 262 TIMER.schedule( handshakeTask, networkLatency ); 263 } 264 }, 265 networkLatency 266 ); 267 } 268 269 public void send( final IDatagram data ) { 270 if ( listener != null ) { 271 Util.log.println( name + ": send data " + data ); 272 TIMER.schedule( 273 new TimerTask() { 274 public void run() { 275 Util.log.println( name + ": wasSent " + data ); 276 listener.wasSent( data ); 277 if ( data instanceof SystemAction ) { 278 final SystemAction sa = ( SystemAction )data; 279 if ( sa.type() == SystemAction.SET_PLAYER ) { 280 throw new IllegalStateException( "Can't be SET_PLAYER to server" ); 281 } 282 if ( sa.type() == SystemAction.YOUR_TURN ) { 283 packet(); 284 } 285 } 286 } 287 }, 288 2 * networkLatency 289 ); 290 } 291 } 292 293 private void packet() { 294 try { 295 if ( is.available() > 0 ) { 296 final GenericDatagram aPacket = new GenericDatagram( is ); 297 final GenericDatagram saPacket = new GenericDatagram( is ); 298 Thread.sleep( 5 * networkLatency ); 299 TIMER.schedule( 300 new TimerTask() { 301 public void run() { 302 Util.log.println( name + ":recv emulation..." ); 303 304 Util.log.println( name + ":recv " + aPacket.wrapped() ); 305 listener.received( aPacket.wrapped() ); 306 307 Util.log.println( name + ":recv " + saPacket.wrapped() ); 308 listener.received( saPacket.wrapped() ); 309 } 310 }, 311 ( ( Action )aPacket.wrapped() ).duration() 312 ); 313 } else { 314 listener.received( SystemAction.surrender( player ) ); 315 } 316 } catch ( Exception e ) { 317 e.printStackTrace(); 318 } 319 } 320 321 public void close( final boolean safe ) { 322 listener.closed(); 323 } 325 324 326 325 public Throwable getError() { … … 329 328 } 330 329 331 private static class QueryDeviceProcess extends TimerTask implements IAsyncProcess { 332 private final IClientListener l; 333 private final DebugRemote remote; 334 335 public QueryDeviceProcess( final DebugRemote remote, 336 final IClientListener l ) { 337 this.remote = remote; 338 this.l = l; 339 } 340 341 public void run() { 342 final int rnd = random.nextInt( 5 ); 343 final IRemoteNode[] servers = new IRemoteNode[rnd]; 344 for( int i = 0; i < servers.length; i++ ) { 345 servers[i] = remote.new ServerRemoteNode( i + 1 ); 346 } 347 l.finished( servers ); 348 } 349 350 public int status() { 351 return 0; 352 } 353 354 public void stop( final int waitMillis ) { 355 cancel(); 356 synchronized( this ) { 357 try { 358 wait( waitMillis ); 359 } catch( InterruptedException e ) { 360 } 361 } 362 } 363 364 public IAsyncProcessListener getListener() { 365 return l; 366 } 367 } 330 /** 331 * todo òóò ñîâñåì óæå äàëåêî îò êîíòðàêòà IAsyncProcess 332 */ 333 private static class QueryDeviceProcess extends TimerTask implements IAsyncProcess { 334 private final IClientListener l; 335 private final DebugRemote remote; 336 private int status = NOT_STARTED; 337 338 public QueryDeviceProcess( final DebugRemote remote, 339 final IClientListener l ) { 340 this.remote = remote; 341 this.l = l; 342 status = IN_PROCESS; 343 } 344 345 public void run() { 346 final int rnd = random.nextInt( 5 ); 347 final IRemoteNode[] servers = new IRemoteNode[rnd]; 348 for ( int i = 0; i < servers.length; i++ ) { 349 servers[i] = remote.new ServerRemoteNode( i + 1 ); 350 } 351 status = SUCCEEDED; 352 l.finished( servers ); 353 } 354 355 public int status() { 356 return status; 357 } 358 359 public Throwable getError() { 360 return null; 361 } 362 363 public void stop( final int waitMillis ) { 364 cancel(); 365 synchronized ( this ) { 366 try { 367 wait( waitMillis ); 368 } catch ( InterruptedException e ) { 369 } 370 } 371 status = INTERRUPTED; 372 l.finished( null ); 373 } 374 375 public IAsyncProcessListener getListener() { 376 return l; 377 } 378 } 368 379 } -
chess/src/chess/ui/ChessMIDlet.java
r29 r34 49 49 private final Screen choosePlayerForm = new ChoosePlayerScreen( this ); 50 50 private final GameCanvas gameCanvas = new GameCanvas( this ); 51 private final Wait Screen waitScreen = new WaitScreen(51 private final WaitCanvas waitScreen = new WaitCanvas( 52 52 this, 53 53 MSG.getMessage( "wait-for-bluetooth.title" ), -
chess/src/chess/ui/GameCanvas.java
r28 r34 61 61 private static final int LABELS_COLOR = 0; 62 62 63 public final Wait ScreenwaitScreen;63 public final WaitCanvas waitScreen; 64 64 65 65 public final Command surrenderCommand = new Command( MSG.getMessage( "command.surrender" ), Command.CANCEL, 1 ); … … 74 74 downKey = getKeyCode( DOWN ); 75 75 76 waitScreen = new Wait Screen(76 waitScreen = new WaitCanvas( 77 77 midlet, 78 78 MSG.getMessage( "wait.title" ), -
chess/src/chess/ui/JoinGameScreen.java
r29 r34 56 56 public void refresh( final boolean force ) { 57 57 this.force = force; 58 midlet.display.setCurrent( scanningNetworkAlert ); 59 // if ( force && midlet.display.getCurrent() == this ) { 60 // } 58 midlet.display.setCurrent( scanningNetworkAlert ); 61 59 ensureSearcherClosed(); 62 60 asyncProcess = midlet.getRemoteManager().getAvailable( this.force, this ); … … 68 66 nodes = servers; 69 67 70 //todo check asyncProcess.status() and display error message71 72 68 final boolean nothingFound = ( servers == null || servers.length == 0 ); 73 69 if ( nothingFound ) { 74 if ( force ) { 70 final int status = asyncProcess.status(); 71 if ( status == IAsyncProcess.FAILED ) { 72 final Throwable e = asyncProcess.getError(); 73 if ( e != null ) { 74 final Alert alert = new Alert( "Error", e.getMessage(), null, AlertType.ERROR ); 75 midlet.display.setCurrent( alert, this ); 76 } 77 } else if ( status == IAsyncProcess.INTERRUPTED ) { 78 final Alert alert = new Alert( 79 "Warning", 80 "Search interrupted", 81 null, 82 AlertType.INFO 83 ); 84 midlet.display.setCurrent( alert, this ); 85 } else if ( force ) { 75 86 //åñëè èñêàëè â ñåòè è íè÷åãî íå íàøëè -- íå ñóäüáà 76 87 midlet.display.setCurrent( nothingFoundAlert, this ); … … 82 93 * è, çàîäíî, äàòü îáíîâèòüñÿ ýêðàíó 83 94 */ 84 midlet.display.callSerially( this ); 95 //midlet.display.callSerially( this ); 96 refresh( true ); 85 97 } 86 98 } else { … … 121 133 if ( asyncProcess != null ) { 122 134 asyncProcess.stop( 1000 ); 123 asyncProcess = null;135 //asyncProcess = null; 124 136 } 125 137 } -
chess/src/chess/ui/WaitScreen.java
r14 r34 29 29 text.setLayout( Item.LAYOUT_EXPAND | Item.LAYOUT_VCENTER ); 30 30 append( text ); 31 32 //append( new Gauge( "test-1", true, 100, 35 ) );33 //append( new Gauge( "test-2", true, 100, 45 ) );34 31 } 35 32
Note: See TracChangeset
for help on using the changeset viewer.