Exemplo n.º 1
0
  public Cliente(Socket s) {
    super("OPERACIONES CON BD");
    socket = s;
    try {
      salida = new DataOutputStream(socket.getOutputStream());
      inObjeto = new ObjectInputStream(socket.getInputStream());
    } catch (IOException e) {
      e.printStackTrace();
      System.exit(0);
    }
    setLayout(null);
    etiqueta.setBounds(10, 10, 200, 30);
    add(etiqueta);
    empconsultar.setBounds(210, 10, 50, 30);
    add(empconsultar);

    textarea1 = new JTextArea();
    scrollpane1 = new JScrollPane(textarea1);
    scrollpane1.setBounds(10, 50, 400, 300);
    add(scrollpane1);
    boton.setBounds(420, 10, 100, 30);
    add(boton);
    desconectar.setBounds(420, 50, 100, 30);
    add(desconectar);

    textarea1.setEditable(false);
    boton.addActionListener(this);
    desconectar.addActionListener(this);
    setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
  }
 /** Start talking to the server */
 public void start() {
   String codehost = getCodeBase().getHost();
   if (socket == null) {
     try {
       // Open the socket to the server
       socket = new Socket(codehost, port);
       // Create output stream
       out = new ObjectOutputStream(socket.getOutputStream());
       out.flush();
       // Create input stream and start background
       // thread to read data from the server
       in = new ObjectInputStream(socket.getInputStream());
       new Thread(this).start();
     } catch (Exception e) {
       // Exceptions here are unexpected, but we can't
       // really do anything (so just write it to stdout
       // in case someone cares and then ignore it)
       System.out.println("Exception! " + e.toString());
       e.printStackTrace();
       setErrorStatus(STATUS_NOCONNECT);
       socket = null;
     }
   } else {
     // Already started
   }
   if (socket != null) {
     // Make sure the right buttons are enabled
     start_button.setEnabled(false);
     stop_button.setEnabled(true);
     setStatus(STATUS_ACTIVE);
   }
 }
Exemplo n.º 3
0
  // **********************************************************************************
  //
  // Theoretically, you shouldn't have to alter anything below this point in this file
  //      unless you want to change the color of your agent
  //
  // **********************************************************************************
  public void getConnected(String args[]) {
    try {
      // initial connection
      int port = 3000 + Integer.parseInt(args[1]);
      s = new Socket(args[0], port);
      sout = new PrintWriter(s.getOutputStream(), true);
      sin = new BufferedReader(new InputStreamReader(s.getInputStream()));

      // read in the map of the world
      numNodes = Integer.parseInt(sin.readLine());
      int i, j;
      for (i = 0; i < numNodes; i++) {
        world[i] = new node();
        String[] buf = sin.readLine().split(" ");
        world[i].posx = Double.valueOf(buf[0]);
        world[i].posy = Double.valueOf(buf[1]);
        world[i].numLinks = Integer.parseInt(buf[2]);
        // System.out.println(world[i].posx + ", " + world[i].posy);
        for (j = 0; j < 4; j++) {
          if (j < world[i].numLinks) {
            world[i].links[j] = Integer.parseInt(buf[3 + j]);
            // System.out.println("Linked to: " + world[i].links[j]);
          } else world[i].links[j] = -1;
        }
      }
      currentNode = Integer.parseInt(sin.readLine());

      String myinfo =
          args[2] + "\n" + "0.7 0.45 0.45\n"; // name + rgb values; i think this is color is pink
      // send the agents name and color
      sout.println(myinfo);
    } catch (IOException e) {
      System.out.println(e);
    }
  }
Exemplo n.º 4
0
 /**
  * ** Reads a line from the specified socket's input stream ** @param socket The socket to read a
  * line from ** @param maxLen The maximum length of of the line to read ** @param sb The string
  * buffer to use ** @throws IOException if an error occurs or the server has stopped
  */
 protected static String socketReadLine(Socket socket, int maxLen, StringBuffer sb)
     throws IOException {
   if (socket != null) {
     int dataLen = 0;
     StringBuffer data = (sb != null) ? sb : new StringBuffer();
     InputStream input = socket.getInputStream();
     while ((maxLen < 0) || (maxLen > dataLen)) {
       int ch = input.read();
       // Print.logInfo("ReadLine char: " + ch);
       if (ch < 0) {
         // this means that the server has stopped
         throw new IOException("End of input");
       } else if (ch == LineTerminatorChar) {
         // include line terminator in String
         data.append((char) ch);
         dataLen++;
         break;
       } else {
         // append character
         data.append((char) ch);
         dataLen++;
       }
     }
     return data.toString();
   } else {
     return null;
   }
 }
Exemplo n.º 5
0
 public ServerAgentThread(Server father, Socket sc) {
   this.father = father;
   this.sc = sc;
   try {
     din = new DataInputStream(sc.getInputStream());
     dout = new DataOutputStream(sc.getOutputStream());
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Exemplo n.º 6
0
 public Client(int port) {
   Socket socket = null;
   try {
     socket = new Socket("127.0.0.1", port);
     chatField.setText("------CONNECTION ESTABLISHED------");
     out = new PrintWriter(socket.getOutputStream(), true);
     in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
     enableChat();
   } catch (Exception e) {
     chatField.setText("Connection Failed");
   }
 }
Exemplo n.º 7
0
  // 서버와 연결
  public void connection() {
    try {
      s = new Socket("localhost", 65535); // s=>server
      in = new BufferedReader(new InputStreamReader(s.getInputStream())); // 서버로 값을 읽어들임
      out = s.getOutputStream(); // 서버로 값을 보냄
      /*out.write((Function.LOGIN+"|"+id+"|"
      +pass+"\n").getBytes());*/
    } catch (Exception ex) {
    }

    new Thread(this).start(); // run()으로 이동  // 서버로부터 응답값을 받아서 처리
  }
Exemplo n.º 8
0
 public Server(int port) {
   ServerSocket serverSocket = null;
   try {
     serverSocket = new ServerSocket(port);
     clientSocket = serverSocket.accept();
     chatField.setText("------CONNECTION ESTABLISHED------");
     out = new PrintWriter(clientSocket.getOutputStream(), true);
     in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
     enableChat();
   } catch (IOException e) {
     chatField.setText("Connection Fail");
   }
 }
  /**
   * run will be exicuted when the thread is called, and will connect to the server and start
   * communicating with it.
   */
  public void run() {
    WaitForConnection wfc = new WaitForConnection("Waiting For Connection");
    m_OldWindow.setEnabled(false);
    try {
      m_Socket = new Socket(m_IP, m_Port);

      // System.out.println("Connecting to ChatService...");
      m_ChatSocket = new Socket(m_IP, m_Port);
      // System.out.println("\nConnected to ChatService...");

      wfc.updateMessage("Waiting For Other Players");

      // System.out.println("Getting OutputStream Stream From server...");
      toServer = new ObjectOutputStream(m_Socket.getOutputStream());
      toChatServer = new ObjectOutputStream(m_ChatSocket.getOutputStream());
      toChatServer.flush();

      // System.out.println("Getting Input Stream From server...");
      fromServer = new ObjectInputStream(m_Socket.getInputStream());
      fromChatServer = new ObjectInputStream(m_ChatSocket.getInputStream());

      m_ChatService = new ChatService();
      m_ChatServiceThread = new Thread(m_ChatService);
      m_ChatServiceThread.start();

      m_MultiPlayerMenu.startGame();
      wfc.dispose();
      m_OldWindow.dispose();
    } catch (java.net.ConnectException e) {
      wfc.dispose();
      MenuWindow menu = new MenuWindow(new JFrame(""));
      JOptionPane.showMessageDialog(menu.getMainFrame(), "Error Connection refused");
      m_OldWindow.setEnabled(true);
    } catch (IOException ex) {
      System.err.print(ex);
    }
  }
Exemplo n.º 10
0
  // メッセージ監視用のスレッド
  public void run() {
    try {
      InputStream input = socket.getInputStream();
      BufferedReader reader = new BufferedReader(new InputStreamReader(input));
      while (!socket.isClosed()) {
        String line = reader.readLine();

        String[] msg = line.split(" ", 2);
        String msgName = msg[0];
        String msgValue = (msg.length < 2 ? "" : msg[1]);

        reachedMessage(msgName, msgValue);
      }
    } catch (Exception err) {
    }
  }
Exemplo n.º 11
0
 public void connect(String user, String pass) {
   if (!connected) {
     try {
       socket = new Socket(domain, 4446);
       out = new PrintWriter(socket.getOutputStream(), true);
       // in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
       in = new ObjectInputStream(socket.getInputStream());
     } catch (java.net.UnknownHostException e) {
       System.err.println("Don't know about host");
       return;
     } catch (IOException e) {
       System.err.println("Couldn't get I/O for the connection to");
       return;
     }
     this.connected = true;
     rec = new Receiver(in);
     rec.start();
   }
 }
Exemplo n.º 12
0
  @Override
  public void run() {
    // TODO Auto-generated method stub
    try {
      Socket s = new Socket(hostin, portin);
      InputStream ins = s.getInputStream();
      OutputStream os = s.getOutputStream();
      ir = new BufferedReader(new InputStreamReader(ins));
      pw = new PrintWriter(new OutputStreamWriter(os), true);

      pw.print(nick);
      while (true) {
        String line = ir.readLine();
        jta.append(line + "\n");
        jsp.getVerticalScrollBar().setValue(jsp.getVerticalScrollBar().getMaximum());
      }

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 13
0
 /**
  * ** Reads the specified number of bytes from the specifed socket ** @param socket The socket
  * from which bytes are read ** @param length The number of bytes to read from the socket
  * ** @throws IOException if an error occured or the server has stopped
  */
 protected static byte[] socketReadBytes(Socket socket, int length) throws IOException {
   if (socket == null) {
     return null;
   } else if (length <= 0) {
     return new byte[0];
   } else {
     int dataLen = 0;
     byte data[] = new byte[length];
     InputStream input = socket.getInputStream();
     while (dataLen < length) {
       int ch = input.read();
       if (ch < 0) {
         // this means that the server has stopped
         throw new IOException("End of input");
       } else {
         data[dataLen] = (byte) ch;
         dataLen++;
       }
     }
     return data;
   }
 }
Exemplo n.º 14
0
    public void run() {
      try {

        DataInputStream dis = new DataInputStream(s.getInputStream());
        String str = dis.readUTF();
        while (str != null && str.length() != 0) {
          System.out.println(str);
          for (Iterator it = cClient.iterator(); it.hasNext(); ) {
            ClientConn cc = (ClientConn) it.next();
            if (this != cc) {
              cc.send(str);
            }
          }
          str = dis.readUTF();
          // send(str);
        }
        this.dispose();
      } catch (Exception e) {
        System.out.println("client quit");
        this.dispose();
      }
    }
Exemplo n.º 15
0
  // {{{ run() method
  public void run() {
    for (; ; ) {
      if (abort) return;

      Socket client = null;
      try {
        client = socket.accept();

        // Stop script kiddies from opening the edit
        // server port and just leaving it open, as a
        // DoS
        client.setSoTimeout(1000);

        Log.log(Log.MESSAGE, this, client + ": connected");

        DataInputStream in = new DataInputStream(client.getInputStream());

        if (!handleClient(client, in)) abort = true;
      } catch (Exception e) {
        if (!abort) Log.log(Log.ERROR, this, e);
        abort = true;
      } finally {
        /* if(client != null)
        {
        	try
        	{
        		client.close();
        	}
        	catch(Exception e)
        	{
        		Log.log(Log.ERROR,this,e);
        	}

        	client = null;
        } */
      }
    }
  } // }}}
Exemplo n.º 16
0
 /**
  * ** Reads the bytes from the specifed socket until an eod-of-stream error occurs, or ** until
  * the maximum number of bytes has bee read. ** @param socket The socket from which bytes are read
  * ** @param baos The ByteArrayOutputStream to which the bytes are written ** @param maxLength The
  * number of bytes to read from the socket ** @return The number of bytes read if no exception has
  * occurred ** @throws IOException if an error occured or the server has stopped
  */
 protected static int socketReadBytes(Socket socket, ByteArrayOutputStream baos, int maxLength)
     throws IOException {
   if (socket == null) {
     return 0;
   } else if (maxLength == 0) {
     return 0;
   } else {
     int dataLen = 0;
     InputStream input = socket.getInputStream();
     while ((maxLength < 0) || (dataLen < maxLength)) {
       int ch = input.read();
       if (ch < 0) {
         // we've reached the end of input
         return dataLen;
       } else {
         if (baos != null) {
           baos.write(ch);
         }
         dataLen++;
       }
     }
     return dataLen;
   }
 }
Exemplo n.º 17
0
  public void launchChess() {

    mainWindow = new JFrame("网络黑白棋	作者:张炀");
    jpWest = new JPanel();
    jpEast = new JPanel();
    jpNorth = new JPanel();
    jpSouth = new JPanel();
    jpCenter = new JPanel();

    turnLabel = new JLabel();
    blackNumberLabel = new JLabel("黑棋:\n" + black + "		");
    whiteNumberLabel = new JLabel("白棋:\n" + white + "		");
    timeLabel = new JLabel("时间:  " + time + "		s");
    noticeLabel = new JLabel();

    noticeLabel = new JLabel("请选择:");
    numberPane = new JPanel();
    readyPane = new JPanel();
    jt1 = new JTextField(18); // 发送信息框
    jt2 = new JTextArea(3, 30); // 显示信息框
    js = new JScrollPane(jt2);
    jt2.setLineWrap(true);
    jt2.setEditable(false);
    //		jt1.setLineWrap(true);

    send = new JButton("发送");
    cancel = new JButton("取消");
    regret = new JButton("悔棋");
    submit = new JButton("退出");
    begin = new JButton("开始");
    save = new JButton("存盘");

    save.setEnabled(true);
    begin.setEnabled(true);

    fighter = new JRadioButton("下棋");
    audience = new JRadioButton("观看");
    group = new ButtonGroup();
    group.add(audience);
    group.add(fighter);
    group.add(AIPlayer);

    submit.addActionListener(this);
    begin.addActionListener(this);
    save.addActionListener(this);
    send.addActionListener(this);
    cancel.addActionListener(this);
    regret.addActionListener(this);
    fighter.addActionListener(this);
    audience.addActionListener(this);

    jpNorth.setLayout(new BorderLayout());
    jpNorth.add(turnLabel, BorderLayout.NORTH);
    jpNorth.add(jpCenter, BorderLayout.CENTER);
    jpSouth.add(js);
    jpSouth.add(jt1);
    jpSouth.add(send);
    jpSouth.add(cancel);
    jpEast.setLayout(new GridLayout(3, 1));
    submit.setBackground(new Color(130, 251, 241));
    panel x = new panel();
    jpEast.add(x);
    jpEast.add(numberPane);
    jpEast.add(readyPane);

    numberPane.add(blackNumberLabel);
    numberPane.add(whiteNumberLabel);
    numberPane.add(timeLabel);
    numberPane.add(submit);
    numberPane.add(begin);
    numberPane.add(save);
    numberPane.add(regret);

    readyPane.add(noticeLabel);
    readyPane.add(fighter);
    readyPane.add(audience);
    //		readyPane.add(save);
    //		readyPane.add(regret);

    jpCenter.setSize(400, 400);
    jmb = new JMenuBar();
    document = new JMenu("游戏		");
    edit = new JMenu("设置		");
    insert = new JMenu("棋盘			");
    help = new JMenu("帮助		");
    jmb.add(document);
    jmb.add(edit);
    jmb.add(insert);
    jmb.add(help);
    // mainWindow.setJMenuBar(jmb);

    mainWindow.setBounds(80, 80, 600, 600);
    mainWindow.setResizable(false);

    jsLeft = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true, jpNorth, jpSouth);
    jsBase = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, jsLeft, jpEast);

    mainWindow.add(jsBase);
    mainWindow.setVisible(true);
    mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    jsBase.setDividerLocation(0.7);
    jsLeft.setDividerLocation(0.78);

    jpCenter.setLayout(new GridLayout(8, 8, 0, 0));
    ImageIcon key = new ImageIcon("chess1.jpg");
    for (int i = 0; i < cell.length; i++)
      for (int j = 0; j < cell.length; j++) {
        cell[i][j] = new ChessBoard(i, j);
        cell[i][j].addMouseListener(this);
        jpCenter.add(cell[i][j]);
      }

    cell[3][3].state = cell[4][4].state = '黑';
    cell[4][3].state = cell[3][4].state = '白';
    cell[3][3].taken = cell[4][4].taken = true;
    cell[4][3].taken = cell[3][4].taken = true;

    RememberState();

    new Thread(new TurnLabel(this)).start();

    file = new File("D:/" + myRole);
    try {
      fout = new FileOutputStream(file);
      out = new ObjectOutputStream(fout);
    } catch (IOException e1) {
      e1.printStackTrace();
    }

    Connect();

    try {
      out99 = new ObjectOutputStream(socket99.getOutputStream());
      in99 = new ObjectInputStream(socket99.getInputStream());

      out66 = new ObjectOutputStream(socket66.getOutputStream());
      in66 = new ObjectInputStream(socket66.getInputStream());

      out88 = new DataOutputStream(socket88.getOutputStream());
    } catch (IOException e) {
      e.printStackTrace();
    }

    new Thread(new Client9999(this)).start();
    new Thread(new Client6666(this)).start();
  }
Exemplo n.º 18
0
    @Override
    public void run() {

      try {
        // Create data input and output streams
        DataInputStream inputFromClient = new DataInputStream(socket.getInputStream());
        DataOutputStream outputToClient = new DataOutputStream(socket.getOutputStream());

        // Set up a byte buffer to capture the file from the client
        byte[] buffer = new byte[BUFFER_SIZE];
        OutputStream outputStream = null;
        String fileName = "";
        boolean createFile = true;
        int bytesReceived = 0;
        long totalBytesReceived = 0;
        long fileSize = 0;

        // Continuously serve the client
        while (true) {
          bytesReceived = inputFromClient.read(buffer);

          if (bytesReceived
              > 0) { // Get the file transmission header from the initial client packet
            String transmitHeader = new String(buffer, 0, bytesReceived);
            // transmitHeader = transmitHeader.substring(0, bytesReceived).trim().;
            String[] header = transmitHeader.split(HEADER_DEL);
            fileSize = Long.parseLong(header[0]);
            fileName = header[1];

            // Send receipt acknowledgment back to the client. Just send back the number of bytes
            // received.
            outputToClient.writeInt(bytesReceived);

            // Reinitialize buffer values
            buffer = new byte[BUFFER_SIZE];
            bytesReceived = 0;
          }

          // Wait for client to send bytes
          while ((bytesReceived = inputFromClient.read(buffer)) != -1) {
            if (inputFromClient.available() > 0) {
              if (createFile) { // Get a unique name for the file to be received
                fileName = textFolder.getText() + fileName; // getUniqueFileName();
                outputStream = createFile(fileName);
                createFile = false;
                textArea.append("Receiving file from client.\n");
              }

              // Write bytes to file
              outputStream.write(buffer, 0, bytesReceived);
            } else { // We get here if no more data is available, but some bytes were already
              // received

              // If bytes were received and the file wasn't already created,
              // it means that the file was smaller than our buffer size.
              // Create the file...
              if (bytesReceived > 0
                  && createFile) { // Get a unique name for the file to be received
                fileName = textFolder.getText() + fileName; // getUniqueFileName();
                outputStream = createFile(fileName);
                createFile = false;
                textArea.append("Receiving file from client.\n");
              }

              if (outputStream != null) {
                if (bytesReceived > 0) { // Write remaining bytes to file, if any
                  outputStream.write(buffer, 0, bytesReceived);
                }

                outputStream.flush();
                outputStream.close();
                textArea.append("Received file successfully. Saved as " + fileName + "\n");

                // Return success to client.
                outputToClient.writeInt(0);
              }

              // Reset creation flag
              createFile = true;
              break;
            }

            // Reinitialize buffer values
            buffer = new byte[BUFFER_SIZE];
            bytesReceived = 0;
          }
        }
      } catch (IOException e) {
        System.err.println(e);
      }
    }
Exemplo n.º 19
0
  public void actionPerformed(ActionEvent e) {
    Object source = e.getSource();
    // Client pressed enter in the message entry field-send it
    if (source == enterField) {
      // Get the message
      message = e.getActionCommand();
      try {
        // Encipher the message
        if (message.length() > plaintextBlockSize)
          message = message.substring(0, plaintextBlockSize);
        byte[] ciphertext =
            Ciphers.RSAEncipherWSalt(message.getBytes(), BigIntegerMath.THREE, recipModulus, sr);
        // Send to the server
        output.write(ciphertext);
        output.flush();
        // Display same message in client output area
        displayArea.append("\n" + message);
        enterField.setText("");
      } catch (IOException ioe) {
        displayArea.append("\nError writing message");
      }
    } else if (source == connectButton) {
      if (connection != null) { // Already connected-button press now means disconnect
        try {
          // Send final message of 0
          byte[] lastMsg = new byte[1];
          lastMsg[0] = 0;
          output.write(Ciphers.RSAEncipherWSalt(lastMsg, BigIntegerMath.THREE, recipModulus, sr));
          output.flush();
          // close connection and IO streams, change some components
          closeAll();
        } catch (IOException ioe) {
          displayArea.append("\nError closing connection");
        }
      } else { // Not connected-connect
        // Get name of server to connect to
        chatServer = serverField.getText();
        displayArea.setText("Attempting connection to " + chatServer);
        try {
          // Set up the socket
          connection = new Socket(chatServer, 55555);

          displayArea.append("\nConnected to: " + connection.getInetAddress().getHostName());

          // Set up the IO streams
          output = new DataOutputStream(connection.getOutputStream());
          output.flush();
          input = new DataInputStream(connection.getInputStream());

          // Exchange public keys with the server-send yours, get theirs
          exchangeKeys();

          // Change appearance/functionality of some components
          serverField.setEditable(false);
          connectButton.setLabel("Disconnect from server above");
          enterField.setEnabled(true);
          // Set up a thread to listen for the connection
          listener =
              new Thread(
                  new Runnable() {
                    public void run() {
                      go();
                    }
                  });
          listener.start();
        } catch (IOException ioe) {
          displayArea.append("\nError connecting to " + chatServer);
        }
      }
    }
  }
Exemplo n.º 20
0
  // The main procedure
  public static void main(String args[]) {
    String s;

    initGUI();

    while (true) {
      try { // Poll every ~10 ms
        Thread.sleep(10);
      } catch (InterruptedException e) {
      }

      switch (connectionStatus) {
        case BEGIN_CONNECT:
          try {
            // Try to set up a server if host
            if (isHost) {
              hostServer = new ServerSocket(port);
              socket = hostServer.accept();
            }

            // If guest, try to connect to the server
            else {
              socket = new Socket(hostIP, port);
            }

            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);
            changeStatusTS(CONNECTED, true);
          }
          // If error, clean up and output an error message
          catch (IOException e) {
            cleanUp();
            changeStatusTS(DISCONNECTED, false);
          }
          break;

        case CONNECTED:
          try {
            // Send data
            if (toSend.length() != 0) {
              out.print(toSend);
              out.flush();
              toSend.setLength(0);
              changeStatusTS(NULL, true);
            }

            // Receive data
            if (in.ready()) {
              s = in.readLine();
              if ((s != null) && (s.length() != 0)) {
                // Check if it is the end of a trasmission
                if (s.equals(END_CHAT_SESSION)) {
                  changeStatusTS(DISCONNECTING, true);
                }

                // Otherwise, receive what text
                else {
                  appendToChatBox("INCOMING: " + s + "\n");
                  changeStatusTS(NULL, true);
                }
              }
            }
          } catch (IOException e) {
            cleanUp();
            changeStatusTS(DISCONNECTED, false);
          }
          break;

        case DISCONNECTING:
          // Tell other chatter to disconnect as well
          out.print(END_CHAT_SESSION);
          out.flush();

          // Clean up (close all streams/sockets)
          cleanUp();
          changeStatusTS(DISCONNECTED, true);
          break;

        default:
          break; // do nothing
      }
    }
  }
Exemplo n.º 21
0
 // set up streams
 private void setupStreams() throws IOException {
   output = new ObjectOutputStream(connection.getOutputStream());
   output.flush();
   input = new ObjectInputStream(connection.getInputStream());
   showMessage("\n Streams set up \n");
 }
Exemplo n.º 22
0
  /**
   * Class that contains the main function which creates the window for the game and implements the
   * server/client socket
   */
  @SuppressWarnings("deprecation")
  public static void main(String args[]) {
    int i = -1; // Variable to keep track of the result from the game

    do // Do-while loop
    {

      try {
        JFrame frame = getFrame(); // Create the frame

        // Dialog to get the name from the player as string, put the string in a label
        String sname = returnNameString();
        JLabel label = new JLabel(sname);

        // Create the status bar panel and shove it down the bottom of the frame
        JPanel statusPanel = new JPanel();
        statusPanel.setBorder(new BevelBorder(BevelBorder.LOWERED));
        statusPanel.setBackground(Color.red);
        frame.add(statusPanel, BorderLayout.SOUTH);

        // Create a label, placed at the bottom of the frame
        JLabel statusLabel = new JLabel();
        statusLabel.setHorizontalAlignment(SwingConstants.LEFT);
        statusPanel.add(statusLabel);
        Button clearButton = new Button("Clear"); // Creating a "clear" button
        clearButton.setSize(new Dimension(10, 20));
        statusPanel.add(label);
        statusPanel.add(clearButton); // Adding the button to the panel

        statusPanel.add(getTime()); // Adding the clock to the status panel

        frame.setVisible(true);

        char ch;
        if (args.length == 0) ch = 'O';
        else ch = 'X';

        TicTacPanel ticTacPanel = new TicTacPanel(ch); // Create a panel for the game
        TicTacAction ticTacAction = new TicTacAction(ticTacPanel); // Handle actions in the game

        clearButton.addActionListener(ticTacAction);
        ticTacPanel.addMouseListener(ticTacAction);
        frame.add(ticTacPanel);
        frame.show();

        // Creating socket and I/O stream objects
        Socket s;
        ObjectOutputStream oops;
        ObjectInputStream oips;

        switch (ch) {
          case 'O':
            s = (new ServerSocket(7777)).accept();
            oops = new ObjectOutputStream(s.getOutputStream());
            oops.writeObject(ticTacPanel.ttt);
            ticTacAction.ready = false;
            break;
          case 'X':
          default:
            s = new Socket(args[0], 7777);
            ticTacAction.ready = true;
        }
        while (true) // Infinite loop
        {
          oips = new ObjectInputStream(s.getInputStream());
          ticTacPanel.ttt = (TicTacGame) (oips.readObject());
          ticTacPanel.paint(ticTacPanel.getGraphics());
          ticTacAction.ready = true;
          while (ticTacAction.ready) {
            Thread.sleep(100);
          }
          oops = new ObjectOutputStream(s.getOutputStream());
          oops.writeObject(ticTacPanel.ttt);

          i = ticTacPanel.ttt.checkWin(); // Check if there's a winner
          if (i == 1) // A winner is declared
          {
            TicTacPanel.infoBox("The winner is " + sname + "!", "Game Over");
            ticTacPanel.ttt.clearAll();
            ticTacPanel.paint(ticTacPanel.getGraphics());
          } else if (i == 0) // No winner, but every square is covered so the game is done
          {
            TicTacPanel.infoBox("We have a tie!", "Game Over");
            ticTacPanel.ttt.clearAll();
            ticTacPanel.paint(ticTacPanel.getGraphics());
          }
        }
      } catch (Exception e) {
        System.out.println(e);
        e.printStackTrace();
        System.exit(1);
      }
    } while (i == -1); // End of do-while loop
  }