PageRenderTime 29ms CodeModel.GetById 9ms app.highlight 16ms RepoModel.GetById 0ms app.codeStats 1ms

/duelos_android/src/com/moob/BT/AcceptThread.java

https://bitbucket.org/jgorozco/ejemplosandroid
Java | 356 lines | 252 code | 65 blank | 39 comment | 7 complexity | d1b0a5f3891ab0b4a3bba48956f60ccf MD5 | raw file
  1package com.moob.BT;
  2
  3import java.io.IOException;
  4import java.io.ObjectInputStream;
  5import java.io.ObjectOutputStream;
  6import java.io.OptionalDataException;
  7import com.moob.FB.Utility;
  8import com.moob.frwk.Disparo;
  9import com.moob.frwk.Server;
 10import com.moob.frwk.User;
 11
 12
 13
 14import android.annotation.TargetApi;
 15import android.bluetooth.BluetoothAdapter;
 16import android.bluetooth.BluetoothServerSocket;
 17import android.bluetooth.BluetoothSocket;
 18import android.os.Handler;
 19import android.os.Message;
 20import android.util.Log;
 21import android.view.View;
 22
 23//******************* SERVEUR *********************
 24//@TargetApi(10)
 25public class AcceptThread extends Thread {
 26	   private final BluetoothServerSocket mmServerSocket;
 27	   private BluetoothAdapter bluetoothAdapter;
 28	   private ObjectInputStream  mmInStream=null;
 29       private ObjectOutputStream  mmOutStream=null;
 30	   private String message;
 31	   private boolean open=false;
 32	   private boolean playing=false;
 33	   private boolean waitingShoot=false;
 34	   private boolean sentShoot=false;
 35	   private Handler handler;
 36	   private User user = null;
 37	   private Server server=null;
 38	   private int sdkVersion = 0;
 39	   private Disparo clientShoot=null;
 40	   private Disparo serverShoot=null;	
 41	   public AcceptThread() {
 42		   
 43		   Log.d("trace","Thread Serveur constructeur");
 44	       BluetoothServerSocket tmp = null;
 45	       sdkVersion = android.os.Build.VERSION.SDK_INT; // e.g. sdkVersion := 8;
 46	       try { bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
 47	       Log.d("trace","bt adapter"+bluetoothAdapter.toString());
 48	       /*
 49		       if (sdkVersion>8) //2.3 and more
 50		           tmp = socketSDKversion8plus();
 51		    	   else
 52		    	   tmp = socketSDKversion8andLess();*/
 53	       tmp =bluetoothAdapter.listenUsingRfcommWithServiceRecord("jeu", Utility.uuid);
 54	       } catch (IOException e) { Log.d("trace","error BTadapter : "+e.getMessage());}
 55	       mmServerSocket = tmp;
 56	       server = new Server(bluetoothAdapter.getName(),bluetoothAdapter.getAddress());
 57	       Log.d("trace","creation server : "+server.toString());
 58	   }
 59	   
 60	   @TargetApi(10)
 61	   public BluetoothServerSocket socketSDKversion8plus() throws IOException{
 62		   BluetoothServerSocket tmp = null;
 63		   tmp = bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord("jeu", Utility.uuid);
 64		   Log.d("trace","tmp plus8: "+tmp.toString());
 65		   return tmp;
 66	   }
 67	   public BluetoothServerSocket socketSDKversion8andLess() throws IOException{
 68		   BluetoothServerSocket tmp = null;
 69		   tmp =bluetoothAdapter.listenUsingRfcommWithServiceRecord("jeu", Utility.uuid);
 70		   Log.d("trace","tmp less8: "+tmp.toString());
 71		   return tmp;
 72	   }
 73	   
 74	   @Override
 75	public void run() {
 76	       BluetoothSocket socket = null;
 77	       
 78	       while (true) {
 79	    	   Log.d("trace","Thread Serveur try accecpt");
 80	           try {
 81	               socket = mmServerSocket.accept();
 82	               open=true;
 83	               Log.d("trace","Thread Serveur en attente");
 84	           } catch (IOException e) {
 85	        	   Log.d("trace","Erreur thread serveur"+e.getMessage());
 86	               break;
 87	           }
 88
 89	           if (socket != null) {
 90	        	   Log.d("trace","Thread Serveur connection etablie");
 91	        	   
 92	               manageConnectedSocket(socket);
 93	               try {
 94					mmServerSocket.close();
 95				} catch (IOException e) {
 96					Log.d("trace","Erreur thread serveur"+e.getMessage());
 97					e.printStackTrace();
 98				}
 99	               break;
100	           }
101	       }
102	   }
103
104	   private void manageConnectedSocket(BluetoothSocket socket) {
105		   
106		 //3. get Input and Output streams
107		   try {
108			mmOutStream = new ObjectOutputStream(socket.getOutputStream());
109			mmOutStream.flush();
110			mmInStream = new ObjectInputStream(socket.getInputStream());
111		   } catch (IOException e1) {
112			
113			Log.d("trace",e1.getMessage());
114		   }
115		   
116		
117           Log.d("trace","SERVEUR CONNECTE !!");
118           
119
120       
121         //4. The two parts communicate via the input and output streams
122			while(open){
123				sentShoot=false;
124				try{
125					//**************************************************
126					// WAITING FOR DETECTION
127					Log.d("trace","serveur waiting message");
128					message = (String)mmInStream.readObject();
129					Log.d("trace","MESSAGE RECU SERVEUR : "+message);
130					//user add to view
131					if(message.equals("detection")){
132						Message msg = new Message();
133						msg.obj=message;						
134						msg.what=0; 
135						handler.sendMessage(msg);
136						
137						//**************************************************
138						// STOP AND RESTART
139						//Send to the client a server object witch is serializable via the OutputStream
140		 		   		sendMessage(server);
141		 		   		
142			 		   	msg = new Message();
143						msg.what=1;
144		 		   		handler.sendMessage(msg);
145						}
146					else{
147						if(message.equals("startGame")){
148							Message msg = new Message();
149							msg.obj=message;						
150							msg.what=2; 
151							handler.sendMessage(msg);
152							playing=true;
153						}
154					}
155				}
156				catch(ClassNotFoundException classnot){
157					Log.d("trace","Data received in unknown format");
158					open=false;
159					playing=false;
160				} catch (OptionalDataException e) {
161					Log.d("trace","error serveur????"+e.getMessage());
162					open=false;
163					playing=false;
164				} catch (IOException e) {
165					Log.d("trace","error serveur??"+e.getMessage());
166					open=false;
167					playing=false;
168				}
169			
170			
171			while(playing&&open){
172				sentShoot=false;
173				Log.d("trace","SERVER THREAD WHILE PLAYING");
174				//1 get a random number
175				//2 send it to the client
176				// sleep then vibrate
177				//while
178					//wait for serverUser to shoot OR a shoot from the client
179				
180				//random to send a signal to make both devices vibrating
181				int random = getRandomInt();
182				
183				//**************************************************
184				//Send the random value to the client
185				
186				sendMessage(String.valueOf(random));				
187				//sleep the random time
188				
189				try {
190					sleep(random*1000);
191				} catch (InterruptedException e) {
192					Log.d("trace","SERVER thread SLEEP FAIL");
193					playing=false;
194				}
195				//send value to GameClientActivity because 
196				//Vibrate code must be called with a reference to a Context
197				Message msg2 = new Message();
198				msg2.obj="nothing";						
199				msg2.what=3; 
200				handler.sendMessage(msg2);
201				
202				
203				waitingShoot=true;
204				//WAIT SHOT from him self AND from the client
205				while(waitingShoot){
206					//did the client shooted me ?
207					try{
208						Log.d("trace","SERVER WAITING FOR SHOT");
209						clientShoot = (Disparo)mmInStream.readObject();
210						Log.d("trace","SHOT RECEIVED");
211						//***************
212						Message msg = new Message();
213						msg.what=6;
214						if(clientShoot.getUser().equals("fake")){						
215							//I receive a fake shot to start next round and i won
216							msg.obj="fake";						
217							 
218						}
219						else{
220							//I receive a shot from real user, so i lost and i make death sound
221							msg.obj="lose";	
222						}
223						handler.sendMessage(msg);
224						//***************
225						waitingShoot=false;
226						
227					}
228					catch(ClassNotFoundException classnot){
229						Log.d("trace","555t");waitingShoot=false;open=false;
230						
231					} catch (OptionalDataException e) {
232						Log.d("trace","666");waitingShoot=false;open=false;
233						
234					} catch (IOException e) {
235						Log.d("trace","777");	
236						waitingShoot=false;open=false;
237						
238					}
239				
240					//after shoot and being shooted redo
241					
242					
243				}//end while waitingShoot
244				
245				
246				//TODO : here you have been shoot then you send a fake shoot to play the next round
247				if(!sentShoot){
248					Message msg = new Message();
249					msg.obj="nothing";						
250					msg.what=4; 
251					handler.sendMessage(msg);
252					//WAITING FOR USER TO PRESS NEXT ROUND
253					synchronized(this) {
254				          try {
255				            wait();
256				          } catch(InterruptedException e) {
257				            throw new RuntimeException(e);
258				          }
259					}
260					//********************************
261					Disparo disp = new Disparo("fake", 0, 0,0, 0, null);
262					sendMessage(disp);
263					
264					
265				}
266				else{
267					Log.d("trace","SERVER SHOT SENT");
268				}
269				
270			}//end while playing
271			}//end while open
272 		  
273	}
274	 
275	 
276
277	public void setSentShoot(boolean sentShoot) {
278		this.sentShoot = sentShoot;
279	}
280
281	private int getRandomInt() {
282		 int lower = 1; 
283		 int higher = 5; 
284
285		 return ((int)(Math.random() * (higher+1-lower)) + lower); 
286	}
287
288	public void sendMessage(String msg)
289	 //http://docs.oracle.com/javase/tutorial/essential/io/objectstreams.html
290		{
291			try{
292				
293				mmOutStream.writeObject(msg);
294				mmOutStream.flush();
295				Log.d("trace","server envois >" + msg);
296			}
297			catch(IOException ioException){
298				Log.d("trace","ERROR SEND MESSAGE"+ioException.getMessage());
299			}
300		}
301	 
302	 public void sendMessage(Object obj){ 
303	 //http://developer.android.com/reference/java/io/ObjectOutputStream.html#write(byte[], int, int)
304			
305		 	try{
306				mmOutStream.writeObject(obj);
307				mmOutStream.flush();
308				Log.d("trace","client envois : "+obj.toString());
309			}
310			catch(IOException ioException){
311				Log.d("trace","client ERROR SEND MESSAGE>"+ioException.getMessage());
312			}
313		}
314	 
315	public void cancel() {
316		open=false;
317		
318	       try {
319	    	   
320	    	   mmServerSocket.close();
321	    	   mmInStream.close();
322	    	   mmOutStream.close();	    	   
323	           
324	           Log.d("trace","CLOSE Serveur");
325	       } catch (IOException e) { 
326	    	   Log.d("trace","CLOSE ERROR"+e.getMessage());
327	       }
328	   }
329	
330	public void stopServeur(View v){
331    	try{
332    		Log.d("trace","stop serveur");
333    		this.cancel();
334    		
335    		}
336    	
337    	catch (Exception e){Log.d("trace","stop serveur CATCH"+e.getMessage());}
338    }
339	
340	public void stopServeur(){
341    	try{
342    		Log.d("trace","stop serveur");
343    		this.cancel();
344    		
345    		}
346    	
347    	catch (Exception e){Log.d("trace","stop serveur CATCH"+e.getMessage());}
348    }
349	
350	public void setHandler(Handler handler) {
351		 this.handler=handler;
352		
353	}
354	
355	}
356//******************* FIN SERVEUR *********************