熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java高級技術 >> 正文

Java多線程Socket操作猜數游戲樣例[1]

2022-06-13   來源: Java高級技術 

    服務器端程序接受連接並處理客戶端的請求


 ServerAppjava
  package test;
  import javaio*;
  import javanet*;
  /** *//**
   * 服務器端程序
   *
   * @author luxuan修正趙學慶
   *
   */
  public class ServerApp {
  static final int PORT = ;
  private ServerSocket serverSocket;
  private Socket socket;
  private BufferedReader netIn;
  private PrintWriter netOut;
  public ServerApp() throws IOException {
  serverSocket = new ServerSocket(PORT); xxxxcom
  Systemoutprintln(server start);
  while (true) {
  // 等待連接
  socket = serverSocketaccept();
  ServerThread st = new ServerThread(socket);
  new Thread(st)start();
  }
  }
  class ServerThread implements Runnable {
  private Socket socket;
  private int randomNumber;
  private int clientGuessNumber;
  public ServerThread(Socket s) throws IOException {
  socket = s;
  xxxcom
  netIn = new BufferedReader(new InputStreamReader(socketgetInputStream()));
  netOut = new PrintWriter(socketgetOutputStream());
  }
  public void run() {
  Systemoutprintln(client + socketgetInetAddress() + is connect);
  randomNumber = (int) (Mathrandom() * );
  Systemoutprintln(random number is: + randomNumber);
  try {
  clientGuessNumber = IntegerparseInt(netInreadLine());
  Systemoutprintln(client guess number is: + clientGuessNumber);
  xxxx
  for (int i = ; i > ; i) {
  if (clientGuessNumber == randomNumber) {
  netOutprintln(OK恭喜猜對了);
  ClientAppfinished = true;
  } else if (clientGuessNumber < randomNumber) {
  netOutprintln(您猜的數小了您還有 + (i ) + 次機會);
  ClientAppfinished = false;
  } else if (clientGuessNumber > randomNumber) { xxxcom
  netOutprintln(您猜的數大了您還有 + (i ) + 次機會);
  ClientAppfinished = false;
  }
  netOutflush();
  if (!ClientAppfinished) {
  clientGuessNumber = IntegerparseInt(netInreadLine());
  } else {
  break;
  }
  } xxxx
  if (!ClientAppfinished) {
  netOutprintln(OK您沒有機會了游戲結束);
  }
  ClientAppfinished = true;
  } catch (IOException e) {
  } finally {
  try {
  netOutclose();
  netInclose();
  socketclose();
  } catch (IOException ee) { xxxxxx@com
  }
  }
  }
  }
  public static void main(String[] args) throws IOException {
  new ServerApp();
  }
  }

[]  []  


From:http://tw.wingwit.com/Article/program/Java/gj/201311/27731.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.