//10.3.3  Ӧ¼
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class KeyEvent extends MIDlet {
    Display display;
    Command exit;

    public KeyEvent() {
        display = Display.getDisplay(this);
    }

    public void destroyApp (boolean unconditional) {
    }

    public void pauseApp () {
        System.out.println("App paused.");
    }

    public void startApp () {
       display = Display.getDisplay(this);

       // 
       Canvas canvas = new Canvas() { 

         public void paint(Graphics g) { }

         protected void keyPressed(int keyCode) {  // ̰¼
           if (keyCode > 0) {
             System.out.println("keyPressed " + ((char)keyCode));
           } else {
             System.out.println("keyPressed action " + getGameAction(keyCode));
           }                  
         }

         protected void keyReleased(int keyCode) {  // ͷ¼
           if (keyCode > 0) {
             System.out.println("keyReleased " + ((char)keyCode));
           } else {
             System.out.println("keyReleased action " + getGameAction(keyCode));
           } 
         }
      }; // end of anonymous class

      exit = new Command("Exit", Command.STOP, 1);
      canvas.addCommand(exit);
      canvas.setCommandListener(new CommandListener() {
        public void commandAction(Command c, Displayable d) {
          if(c == exit) {  // ˳
            notifyDestroyed();
          } else {
            System.out.println("Saw the command: "+c);
          }
        }
      });
      display.setCurrent(canvas);
    }
}



//10.4.3  ʾظ
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class HappyFace2 extends MIDlet implements AppExiter
{
   /**
    * MIDletʼʱִ
    */
   protected void startApp() 
   {
      // Ļ
      Display.getDisplay(this).setCurrent(new HappyFaceScreen(this));
   }

   /**
    * MIDletͣʱִ
    */
   protected void pauseApp() 
   {
      // ִд
   }

   /**
    * MIDletֹͣʱִ
    */
   protected void destroyApp(boolean unconditional) 
   {
      notifyDestroyed();
   }

   /**
    * MIDlet˳ʱִ
    */
   public void exitApp() 
   {
      destroyApp(true);
   }
}

class HappyFaceScreen extends Canvas implements CommandListener, KeyRepeater
{
   // ƶٶصһЩ
   private int          m_maxX = getWidth() - 1;
   private int			m_maxY = getHeight() - 1;
   private int			m_imageWidth;
   private int			m_imageHeight;
   // ƶصһЩֵ
   private int			m_x = m_maxX / 2;
   private int			m_prevX = m_maxX / 2;
   private int			m_y = m_maxY / 2;
   private int			m_prevY = m_maxY / 2;
   private AppExiter	m_appExiter;
   private Image		m_face;
   private KeyRepeat	m_repeat = new KeyRepeat(this);

   /**
    * 캯ͼƬ,ʼ. 
    * ȻEXITť
    */
   public HappyFaceScreen(AppExiter exiter)
   {
      m_appExiter = exiter;
      
      try
      {
         m_face = Image.createImage("/face.png");
      }
      catch (Exception e)
      {
         m_face = null;
      }

      // һЩֵ
      m_imageWidth = m_face.getWidth();
      m_imageHeight = m_face.getHeight();
      // EXITť
      addCommand(AppExiter.EXIT);
      // Ǽ¼
      setCommandListener(this);
      m_repeat.setSleepPeriod(20);
      m_repeat.start();
   }
   
   /**
    * ĻϻеĲ
    *
    * g ҪƵĲ
    */
   protected void paint(Graphics g)
   {
      // ɵĻ
      g.setColor(0xffffff);
      g.fillRect(m_prevX-m_imageWidth/2, 
              m_prevY-m_imageHeight/2, m_imageWidth, m_imageHeight);
      g.setColor(0);
      // µĻ
      g.drawImage(m_face, m_x, m_y, Graphics.VCENTER|Graphics.HCENTER);
      // ʹµλôɵλ
      m_prevX = m_x;
      m_prevY = m_y;
   }

   /**
    * ظʱ
    *
    *  keyCode ǰĴ
    */
   protected void keyRepeated(int keyCode)
   {
      if (hasRepeatEvents())
      {
         performAction(getGameAction(keyCode));
      }
   }

   /**
    * ̰ʱ
    *
    *  keyCode ǰĴ
    */
   protected void keyPressed(int keyCode)
   {
      // MIDP豸֧ظ, 
      // ôʹظģ⹦
      if (!hasRepeatEvents())
      {
         m_repeat.startRepeat(getGameAction(keyCode));
      }
   }

   /**
    * ͷʱ
    *
    *  keyCode ǰĴ
    */
   protected void keyReleased(int keyCode)
   {
      // MIDP 豸֧ظ, 
      //  ôֹͣظģ
      if (!hasRepeatEvents())
      {
         m_repeat.stopRepeat(getGameAction(keyCode));
      }
   }

   /**
    * Ϸģʽʱִ
    */
   public void performAction(int gameAction)
   {
      // ǰӳ
      switch(gameAction)
      {
      case UP:  // 
         if (m_y > 0) m_y--;
         break;
      case LEFT:  
         if (m_x > 0) m_x--;
         break;
      case DOWN:  // 
         if (m_y < m_maxY) m_y++;
         break;
      case RIGHT:  // 
         if (m_x < m_maxX) m_x++;
         break;
      }
      // Ļʾ
      repaint();
   }

   /**
    * ָ밴ʱ
    *
    *  x ָˮƽλ
    *  y ָĴֱλ
    */
   protected void pointerPressed(int x, int y)
   {
      if (hasPointerEvents())
      {
         m_y = y;
         m_x = x;
         repaint();
      }
   }

   /**
    * ָ϶ʱ 
    *  x ָˮƽλ
    *  y ָĴֱλ
    */
   protected void pointerDragged(int x, int y)
   {
      if (hasPointerMotionEvents())
      {
         pointerPressed(x, y);
      }
   }

   public void commandAction(Command c, Displayable d) 
   {
      if (c == AppExiter.EXIT)
      {
         m_repeat.cancel();
         m_repeat = null;
         m_appExiter.exitApp();
      }
   }
}

/**
 * ʹģⰴظ
 */
class KeyRepeat extends Thread
{
   private boolean              m_cancel = false;
   private long                  m_sleepTime = 50;
   private int                   m_gameAction = 0;
   private final KeyRepeater  m_ui;

   public KeyRepeat(KeyRepeater ui)
   {
      m_ui = ui;
   }
   
   /**
    * ֹͣ߳
    */
   public void cancel()
   {
      m_cancel = true;
   }

   /**
    * صǰϷ
    */
   public int getGameAction()
   {
      return m_gameAction;
   }
   
   /**
    * ö¼
    *
    * sleepTimeǶʱ
    */
   public void setSleepPeriod(long sleepTime)
   {
      m_sleepTime = sleepTime;
   }

   /**
    * ʼظ
    */
   public void startRepeat(int gameAction)
   {
      m_gameAction = gameAction;
   }

   /**
    * ֹͣظ
    */
   public void stopRepeat(int gameAction)
   {
      if (gameAction == m_gameAction)
      {
         m_gameAction = 0;
      }
   }

   /**
    * ִظ
    */
   public void run()
   {
      while (!m_cancel)
      {
         // Ҫظ,һ߳
         while (m_gameAction == 0 && !m_cancel)
         {
            Thread.yield();
         }
         // ִظ
         m_ui.performAction(m_gameAction);
         // ȴһʱ
         try
         {
            sleep(m_sleepTime);
         }
         catch (InterruptedException e)
         {
         }
      }
   }
}

/**
 * ûͨ˳
 */
interface AppExiter
{
   /** 
    * һpublicԵEXIT ť,
    *  ڶʹ
    */
   public static final Command EXIT = new Command("Exit", Command.EXIT, 1);

   /**
    * ˳
    */
   public void exitApp();
}

/**
 * ʽģظĽӿ
 */
interface KeyRepeater
{
   /**
    * Ϸģʽʱ,
    *
    */
   public void performAction(int gameAction);
}


//10.4.6  ʾƶͼƶ
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class HappyFace3 extends MIDlet implements AppExiter
{
   /**
    * MIDletʼʱִ
    */
   protected void startApp() 
   {
      // Ļ
      Display.getDisplay(this).setCurrent(new HappyFaceScreen(this));
   }

   /**
    * MIDletͣʱִ
    */
   protected void pauseApp() 
   {
      // ʵִ
   }

   /**
    * MIDletʱִ
    */
   protected void destroyApp(boolean unconditional) 
   {
      notifyDestroyed();
   }

   /**
    * ˳ʱִ
    */
   public void exitApp() 
   {
      destroyApp(true);
   }
}

class HappyFaceScreen extends Canvas implements CommandListener, KeyRepeater
{
   private static final int MAX_SPEED = 15;
   private int          m_horizSpeed = 0;
   private int          m_vertSpeed = 0;
   private int          m_horizDir = 0;
   private int          m_vertDir = 0;

   // ƶٶйصļֵ
   private int          m_maxX = getWidth() - 1;
   private int          m_maxY = getHeight() - 1;
   private int          m_imageWidth;
   private int          m_imageHeight;
   // ƶйصֵ
   private int          m_x = m_maxX / 2;
   private int          m_prevX = m_maxX / 2;
   private int          m_y = m_maxY / 2;
   private int          m_prevY = m_maxY / 2;
   private AppExiter   m_appExiter;
   private Image        m_face;
   private KeyRepeat    m_repeat = new KeyRepeat(this);
   private boolean      m_painting = false;

   /**
    * 캯װͼ,ʼ.
    * EXITť,Ǽ¼
    */
   public HappyFaceScreen(AppExiter exiter)
   {
      m_appExiter = exiter;
      
      try
      {
         m_face = Image.createImage("/face.png");
      }
      catch (Exception e)
      {
         m_face = null;
      }

      // һЩֵ
      m_imageWidth = m_face.getWidth();
      m_imageHeight = m_face.getHeight();
      // EXITť
      addCommand(AppExiter.EXIT);
      // Canavas ǼΪť¼, ô
      // CanavascommandAction() нӦť¼
      setCommandListener(this);
      m_repeat.start();
   }
   
   /**
    * ĻϻеĲ
    *
    * gĻҪƵĲ
    */
   protected void paint(Graphics g)
   {
      if (m_painting) return;

      m_painting = true;
      // ɵ
      g.setColor(0xffffff);
      g.fillRect(m_prevX-m_imageWidth/2, m_prevY-m_imageHeight/2, 
m_imageWidth, m_imageHeight);
      g.setColor(0);
      // µ
      g.drawImage(m_face, m_x, m_y, Graphics.VCENTER|Graphics.HCENTER);
      // ʹµλɵλ
      m_prevX = m_x;
      m_prevY = m_y;
      m_painting = false;
   }

   /**
    * һظʱ
    *
    * keyCodeظµİĴ
    */
   protected void keyRepeated(int keyCode)
   {
      if (hasRepeatEvents())
      {
         performAction(getGameAction(keyCode));
      }
   }

   /**
    * ʱ
    *
    * keyCode ǰĴ
    */
   protected void keyPressed(int keyCode)
   {
      int gameAction = getGameAction(keyCode);
   
      switch (gameAction)
      {
      case UP:  // 
         m_horizDir = -1;
         break;
      case DOWN:  // 
         m_horizDir = 1;
         break;
      case LEFT:  // 
         m_vertDir = -1;
         break;
      case RIGHT:  // 
         m_vertDir = 1;
         break;
      default:
         return;
      }
   
      m_repeat.startRepeat(gameAction);
   }

   /**
    * ͷʱ
    *
    * keyCodeǰĴ
    */
   protected void keyReleased(int keyCode)
   {
      int gameAction = getGameAction(keyCode);
      
      if (gameAction == m_repeat.getGameAction())
      {
         switch (gameAction)
         {
         case UP:
         case DOWN:
            m_horizDir = 0;
            break;
         case LEFT:
         case RIGHT:
            m_vertDir = 0;
            break;
         }
      }
   }

   /**
    * ʹϷģʽʱʹ
    *
    */
   public void performAction(int gameAction)
   {
      // µˮƽλ
      m_horizSpeed += m_horizDir;
      if (m_horizSpeed < -MAX_SPEED)
      {
         m_horizSpeed = -MAX_SPEED;
      }
      else if (m_horizSpeed > MAX_SPEED)
      {
         m_horizSpeed = MAX_SPEED;
      }
      m_y += m_horizSpeed/2;

      // µˮƽλóĻ߽,
      // ôʾĻһ
      if (m_y > m_maxY) 
      {
         m_y = 0;
      }
      else if (m_y < 0) 
      {
         m_y = m_maxY;
      }

      // µĴֱλ
      m_vertSpeed += m_vertDir;
      if (m_vertSpeed < -MAX_SPEED)
      {
         m_vertSpeed = -MAX_SPEED;
      }
      else if (m_vertSpeed > MAX_SPEED)
      {
         m_vertSpeed = MAX_SPEED;
      }
      m_x += m_vertSpeed/2;

      // µĴֱλóĻ߽, 
      // ôʾĻһ
      if (m_x > m_maxX) 
      {
         m_x = 0;
      }
      else if (m_x < 0) 
      {
         m_x = m_maxX;
      }
      // Ļ
      repaint();
   }

   /**
    * ָ밴ʱ
    * xָ뵱ǰˮƽλ
    * yָ뵱ǰֱλ
    */
   protected void pointerPressed(int x, int y)
   {
      if (hasPointerEvents())
      {
         m_y = y;
         m_x = x;
         repaint();
      }
   }

   /**
    * ָ϶ʱ 
    *
    * xָͷʱˮƽλ
    * yָͷʱĴֱλ
    */
   protected void pointerDragged(int x, int y)
   {
      if (hasPointerMotionEvents())
      {
         pointerPressed(x, y);
      }
   }

   public void commandAction(Command c, Displayable d) 
   {
      if (c == AppExiter.EXIT)
      {
         m_repeat.cancel();
         m_repeat = null;
         m_appExiter.exitApp();
      }
   }
}

/**
 * ģظ
 */
class KeyRepeat extends Thread
{
   private Boolean			m_cancel = false;
   private long				m_sleepTime = 50;
   private int				m_gameAction = 0;
   private final KeyRepeater  m_ui;

   public KeyRepeat(KeyRepeater ui)
   {
      m_ui = ui;
   }
   
   /**
    * ֹͣ߳
    */
   public void cancel()
   {
      m_cancel = true;
   }

   /**
    * صǰظϷģʽ
    */
   public int getGameAction()
   {
      return m_gameAction;
   }
   
   /**
    * öʱ
    */
   public void setSleepPeriod(long sleepTime)
   {
      m_sleepTime = sleepTime;
   }

   /**
    * ʼظ
    */
   public void startRepeat(int gameAction)
   {
      m_gameAction = gameAction;
   }

   /**
    * ֹͣظ
    */
   public void stopRepeat(int gameAction)
   {
      if (gameAction == m_gameAction)
      {
         m_gameAction = 0;
      }
   }

   /**
    * ִаظ
    */
   public void run()
   {
      while (!m_cancel)
      {
         // ûаҪظ,һ߳
         while (m_gameAction == 0 && !m_cancel)
         {
            Thread.yield();
         }
         // ظһΰ
         m_ui.performAction(m_gameAction);
         // ȴһʱ
         try
         {
            sleep(m_sleepTime);
         }
         catch (InterruptedException e)
         {
         }
      }
   }
}

/**
 * ִ˳̵Ľӿ
 */
interface AppExiter
{
   /** 
    * ʹpublicEXITť,
    * ڶĻ乫ʹonecd and make a public final.
    */
   public static final Command EXIT = new Command("Exit", Command.EXIT, 1);

   /**
    * ˳ʱ
    */
   public void exitApp();
}

/**
 * ʹģظĽӿ
 */
interface KeyRepeater
{
   public void performAction(int gameAction);
}


//10.8  
import javax.microedition.lcdui.*; 
import javax.microedition.midlet.*; 
  
public class TicTacToe extends MIDlet implements CommandListener { 
  
    // Ļʾ
    private Display theDisplay; 
    private TicTacToeCanvas canvas; 
  
    // ʤϢ
    private String winner = ""; 
    private boolean gameOver = false; 
  
    // Ϸ״̬
    private int whoseturn = 0; 
    private char board[][] = { {'1' , '2' , '3'} , 
                               {'4' , '5' , '6'} , 
                               {'7' , '8' , '9'} }; 
  
    // ˳ť 
    static final Command exitCommand = new Command("Exit",Command.STOP, 1); 
  
    public TicTacToe() 
    { 
        // õʾĻ
        theDisplay = Display.getDisplay(this); 
    } 
  
  
    class TicTacToeCanvas extends Canvas 
    { 
       TicTacToeCanvas() 
       { 
       } 
  
       public void paint(Graphics g) 
       { 
           int width = getWidth(); 
           int height = getHeight(); 
           g.setColor( 0, 0, 0 ); 
           g.fillRect( 0, 0, width, height );   // ĻԭƵͼ
           g.setColor( 255, 255, 255); 
      // 濪ʼ
           String r1 = board[0][0]+"|"+board[0][1]+"|"+board[0][2]+"\n"; 
           String r2 = board[1][0]+"|"+board[1][1]+"|"+board[1][2]+"\n"; 
           String r3 = board[2][0]+"|"+board[2][1]+"|"+board[2][2]; 
           g.drawString("TIC TAC TOE",15,0, Graphics.LEFT|Graphics.TOP); 
           g.drawString(r1,30,15, Graphics.LEFT|Graphics.TOP); 
           g.drawString(r2,30,30, Graphics.LEFT|Graphics.TOP); 
           g.drawString(r3,30,45, Graphics.LEFT|Graphics.TOP); 
           if (winner != "") 
           { 
             g.drawString("WINNER: "+winner,0,60,Graphics.LEFT|Graphics.TOP); 
           } 
           else 
           { 
            g.drawString("TURN: Player "+(whoseturn+1),0,60,
                    Graphics.LEFT|Graphics.TOP); 
           } 
       } 
  
       // 
       protected void keyPressed(int keyCode) { 
        //  X  O
         if (keyCode >= 49 && keyCode <= 57 && !gameOver) 
         { 
            int x = 0, y = 0; 
            keyCode -= 49; 
            if (keyCode < 3) 
            { 
               x = keyCode; 
               y = 0; 
            }  
            else if (keyCode < 6) 
            { 
               x = keyCode-3; 
               y = 1; 
            }  
            else 
            { 
               x = keyCode-6; 
               y = 2; 
            }  
            // ǰλǿյ
          if (board[y][x] != 'X' && board[y][x] != 'O') 
           { 
             if (whoseturn == 0) 
              board[y][x] = 'X'; 
             else 
               board[y][x] = 'O'; 
  
             // һϷ
             whoseturn = 1-whoseturn; 
  
             checkForWinner(); 
  
             // »Ļ
             canvas.repaint(); 
            } 
         } 
       } 
    } 
  
    protected void startApp() throws MIDletStateChangeException 
    { 
       canvas = new TicTacToeCanvas(); 
        
       // ˳ť
       canvas.addCommand(exitCommand); 
       canvas.setCommandListener(this) ; 
  
       theDisplay.setCurrent(canvas); 
    } 
  
    protected void pauseApp() { } 
  
    public void destroyApp(boolean unconditional) 
    { 
    } 
  
    // ¼
    public void commandAction(Command c, Displayable d) 
    { 
      if (c == exitCommand) 
      { 
        destroyApp(false); 
        notifyDestroyed(); 
      } 
    } 
  
    private void checkForWinner() 
    { 
        int i,j; 
        int numXConsec = 0;   // X
        int numOConsec = 0;   // O
  
        boolean tie=true; 
  
        // XO
        for (i=0; i<3; i++) 
        { 
               for (j=0; j<3; j++) 
                       if (board[i][j] != 'X' || board[i][j] != 'O') 
                       { 
                               tie = false; 
                               break; 
                       } 
        } 
        if (tie) 
        { 
               GameOver(-1); 
               return; 
        } 
        
        // ȼˮƽ
        for (i=0; i<3; i++) 
        { 
               numXConsec = numOConsec = 0; 
               for (j=0; j<3; j++) 
               { 
                       if (board[i][j] == 'X') 
                               numXConsec++; 
                       else if (board[i][j] == 'O') 
                               numOConsec++; 
                       else 
                               break; 
               } 
               if (numXConsec > 2) 
               { 
                       GameOver(0); 
                       return; 
               } 
               else if (numOConsec > 2) 
               { 
                       GameOver(1); 
                       return; 
               } 
        } 
        
        // 鴹ֱ
        for (i=0; i<3; i++) 
        { 
               numXConsec = numOConsec = 0; 
               for (j=0; j<3; j++) 
               { 
                       if (board[j][i] == 'X') 
                       { 
                               numXConsec++; 
                       } 
                       else if (board[j][i] == 'O') 
                               numOConsec++; 
                       else 
                               break; 
               } 
               if (numXConsec > 2) 
               { 
                       GameOver(0); 
                       return; 
               } 
               else if (numOConsec > 2) 
               { 
                       GameOver(1); 
                       return; 
               } 
        } 
        
        // Խ
        if ( ((board[0][0] == board[1][1]) && (board[1][1] == board[2][2]) && 
(board[2][2] == 'X')) || 
        ((board[0][2] == board[1][1]) && (board[1][1] == board[2][0]) && 
(board[2][0] == 'X')) ) 
        { 
               GameOver(0); 
               return; 
        } 
        if ( ((board[0][0] == board[1][1]) && (board[1][1] == board[2][2]) && 
(board[2][2] == 'O')) || 
        ((board[0][2] == board[1][1]) && (board[1][1] == board[2][0]) && 
(board[2][0] == 'O')) ) 
        { 
               GameOver(1); 
               return; 
        } 
    } 
  
    private void GameOver(int p) 
    { 
       if (p == -1) 
           winner = "Tie!"; 
       else if (p == 0) 
           winner = "Player 1!"; 
       else 
           winner = "Player 2!"; 
       gameOver = true; 
    } 
} 


//10.9.3  򵥵Ϸ NumberPick
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.util.*;
 
public class NumberPick extends MIDlet implements CommandListener  
{
    // ,һ̨PDAIPַ
    static final String hostname = "myserver.com";
    static final int sendport         = 9000;
    static final int receiveport      = 9001;
 
    static boolean gotResult = false;
 
    private Display myDisplay;
 
    Receive receiveThread = new Receive();
 
    private Alert responseAlert;
 
    private Form searchwait;
    private Form pickscreen;
 
    TextField pickedNumber;
    private Command PICK = new Command("Pick One", Command.OK, 1);
    private Command OK = new Command("Try Again", Command.OK, 1);
 
    public NumberPick() 
    {
    }
 
    public void startApp()
    {
       //  the Pick A NumberĻ
       pickscreen = new Form("Pick A Number");
       pickedNumber = new TextField("Between 0 and 9:","",1, TextField.NUMERIC);
       pickscreen.append(pickedNumber);
       pickscreen.addCommand(PICK);
       pickscreen.setCommandListener(this);
 
       //  Searching, Please Wait screen
       searchwait = new Form("Searching...");
       searchwait.append(new StringItem("Wait","Please wait..."));
       searchwait.addCommand(OK);
       searchwait.setCommandListener(this);
 
       //  Response Alert screen
       responseAlert = new Alert("And Your Guess Is...");
       responseAlert.setTimeout(Alert.FOREVER);
 
       myDisplay = Display.getDisplay(this);
       myDisplay.setCurrent(pickscreen);
 
        // ʼ߳
        receiveThread.start();
    }
 
    public void pauseApp()  
    {
    }
 
    public void destroyApp(boolean unconditional) 
    {
    }
 
    
    public void commandAction(Command c, Displayable d) 
    {
        if (d == pickscreen && c == PICK) 
        {
            String request = pickedNumber.getString();
           if ( !request.equals("") ) 
            {
              myDisplay.setCurrent(searchwait);
              sendPick(request);
           }
        }
    }
 
    void sendPick(String thepick) 
    {
        // pick...
        byte[] message = new byte[1];
        System.arraycopy(thepick.getBytes(), 0, message, 0,1);
 
        DatagramConnection dc = null;
 
        String destAddr = "datagram://" + hostname + ":" + sendport;
 
        try {
            dc = (DatagramConnection)Connector.open(destAddr);
 
           // һݱ׽,Ȼ
            Datagram dgram= dc.newDatagram(message,1,destAddr);
            dc.send(dgram);
            dc.close();
        } 
        catch (Exception e) 
        {
            System.out.println("Connecting Exception: " + e.getMessage());
            if (dc != null) {
                try {
                    dc.close();
                } 
                catch (Exception f)   // 쳣
                {
                   System.out.println("Exception Closing: " + f.getMessage());
                }
            }
        }
    }
 
    class Receive extends Thread 
    {
        public void run() 
        {
            doReceive();
        }
 
        void doReceive() 
        {
            DatagramConnection dc = null;
            Datagram dgram;
 
            try 
            {
            dc = (DatagramConnection)Connector.open("datagram://:"+receiveport);
 
                String reply;
 
                while (true) 
                {
                    dgram = dc.newDatagram(dc.getMaximumLength());
                    dc.receive(dgram);
                    reply = new String(dgram.getData(), 0,dgram.getLength());
                    if (reply.equals("Y"))
                    {
                       responseAlert.setString("100% right!");
                       myDisplay.setCurrent(responseAlert,pickscreen);
                    }
                    else
                    {
                       myDisplay.setCurrent(responseAlert,pickscreen);
                       responseAlert.setString("Wrong as can be!");
                    }
                    try 
                    {
                       Thread.sleep(500);
                    } 
                    catch (Exception e) 
                    { }
                }
 
            } 
            catch (Exception e) 
            {
                System.out.println("Exception: " + e.getMessage());
 
                if (dc != null)  
                {
                    try 
                    {
                        dc.close();
 
                    } 
                    catch (Exception f)   // 쳣
                    {
                        System.out.println("Exception: " + f.getMessage());
                    }
                }
            }
        }
     }
}


//10.9.4  ˵Ĵ
import java.io.*; 
import java.net.*; 
import java.lang.*; 
 
public class NumberServer 
{ 
     public static void main(String args[]) 
     { 
       DatagramSocket receiveSocket = null; 
       try 
       {
         byte[] receiveBytes = new byte[1]; 
         InetAddress receiveAddr = InetAddress.getByName("localhost"); 
         int receivePort = 9000;  // ˿ں
 
         receiveSocket = new DatagramSocket(receivePort, receiveAddr); 
     
         while (true) 
         {
         DatagramPacket receivePacket = new DatagramPacket(receiveBytes, receiveBytes.length);
           receiveSocket.receive(receivePacket);
           String data = new String(receivePacket.getData(), 0, receivePacket.getLength());
           byte[] reply = receivePacket.getData();
           String replyString = new String(reply);
           if (replyString.equals("4"))
               sendResultsBack(true, receivePacket.getAddress());
           else
               sendResultsBack(false, receivePacket.getAddress());
        }
       } 
       catch (Exception e)   // 쳣
       {
          System.err.println("Exception " + e);
       } 
       finally 
       {
         if (receiveSocket != null) 
         {
           try 
           {
              receiveSocket.close(); 
           } 
           catch (Exception e) 
           {
             System.err.println("Exception " + e);
           }
         }
       } 
     } 
   
     // ͻֻ9001˿
     public static void sendResultsBack(boolean rightanswer, InetAddress sendAddr) 
     {
       byte results[] = new byte[1];
       if (rightanswer)
         results[0] = (byte)'Y';
       else
         results[0] = (byte)'N';
       DatagramSocket sendSocket = null; 
       int sendPort = 9001;
       try 
       { 
          sendSocket = new DatagramSocket(); 
          DatagramPacket sendPacket = new DatagramPacket(results,1, sendAddr, sendPort);
          sendSocket.send(sendPacket);
       } 
       catch (Exception e) 
       {
         System.out.println("Exception " + e);
       } 
       finally 
       {
         if (sendSocket != null) 
         {
           try 
           {
              sendSocket.close(); 
           } 
           catch (Exception e) 
           {
             System.err.println("Exception " + e);
           }
         }
       }
     }
}
