예제 #1
0
  public ChatClient(Subject server, Socket socket) throws IOException {
    this.server = server;
    counter++;
    number = counter;
    this.socket = socket;
    // run new thread for listening server
    System.out.println("New ChatClient #" + number + " created");

    inputStream = socket.getInputStream();
    outputStream = socket.getOutputStream();

    // TODO получение имени клиента вставить здесь

    // authorize();

    clientThread = new ClientThread();
    clientThread.start();
  }
  public void start() {
    keepGoing = true;
    /* create socket server and wait for connection requests */
    try {
      // the socket used by the server
      ServerSocket serverSocket = new ServerSocket(port);

      // infinite loop to wait for connections
      while (keepGoing) {
        // format message saying we are waiting
        display("Server menunggu koneksi Client pada port " + port + ".");

        Socket socket = serverSocket.accept(); // accept connection
        // if I was asked to stop
        if (!keepGoing) break;
        ClientThread t = new ClientThread(socket); // make a thread of it
        al.add(t); // save it in the ArrayList
        t.start();
      }
      // I was asked to stop
      try {
        serverSocket.close();
        for (int i = 0; i < al.size(); ++i) {
          ClientThread tc = al.get(i);
          try {
            tc.sInput.close();
            tc.sOutput.close();
            tc.socket.close();
          } catch (IOException ioE) {
            // not much I can do
          }
        }
      } catch (Exception e) {
        display("Exception closing the server and clients: " + e);
      }
    }
    // something went bad
    catch (IOException e) {
      String msg = sdf.format(new Date()) + " Exception on new ServerSocket: " + e + "\n";
      display(msg);
    }
  }