Exemple #1
3
 void send(Scores scoreTable) {
   if (out == null) return;
   try {
     out.reset();
     out.writeObject(scoreTable);
     out.flush();
   } catch (Exception e) {
     ctrl.serverError("Scores Send error!");
   }
 }
Exemple #2
1
 void send(TimeStamp timeStamp) {
   if (out == null) return;
   try {
     out.reset();
     out.writeObject(timeStamp);
     out.flush();
   } catch (Exception e) {
     ctrl.serverError("TimeStamp Send error!");
   }
 }
Exemple #3
1
 void send(PlayersList players) {
   if (out == null) return;
   try {
     out.reset();
     out.writeObject(players);
     out.flush();
   } catch (Exception e) {
     ctrl.serverError("PlayersList Send error!");
   }
 }
Exemple #4
0
 /**
  * * sendResponse checks for the mode of the server and sends a Response object to the client with
  * the appropriate string stored and the client's Cookie.
  *
  * @param clientCookie - Cookie object received by client
  * @param responseToClient - Response object that will be sent to client
  * @param outputObject - Used to write serialized version of object back to client
  * @throws IOException - Thrown if outputObject is interrupted while processing or fails to
  *     process
  */
 static void sendResponse(
     Cookie clientCookie, Response responseToClient, ObjectOutputStream outputObject)
     throws IOException {
   if (mode.getMode() == ServerMode.JOKE) { // If the mode of the server is set to JOKE, send joke
     responseToClient.addResponse(
         joke.say(
             clientCookie
                 .getJokeKey())); // gets joke from Database and stores string in responseToClient
     clientCookie.nextJoke(); // clientCookie increments the index of the joke to be accessed later
     responseToClient.setCookie(clientCookie); // stores clientCookie in responseToClient
     System.out.println("Sending joke response..."); // notify server joke is being sent
     outputObject.writeObject(
         responseToClient); // send a serialized version of Response object to client
   } else if (mode.getMode()
       == ServerMode.PROVERB) { // If the mode of the server is set to PROVERB, send proverb
     responseToClient.addResponse(proverb.say(clientCookie.getProverbKey()));
     clientCookie.nextProverb();
     responseToClient.setCookie(clientCookie);
     System.out.println("Sending proverb response...");
     outputObject.writeObject(
         responseToClient); // send Response object with proverb and client's Cookie to the client
   } else if (mode.getMode()
       == ServerMode
           .MAINTENANCE) { // If the mode of the server is set to MAINTENANCE, notify clients
                           // server is down for maintenance
     responseToClient.addResponse("Joke server temporarily down for maintenance.\n");
     responseToClient.setCookie(clientCookie);
     System.out.println("Sending maintenance response...");
     outputObject.writeObject(
         responseToClient); // send Response object with maintenance message and client's Cookie to
                            // the client
   }
 }
  public void run() {
    try {
      ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
      ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());

      BigInteger bg = dhSpec.getG();
      BigInteger bp = dhSpec.getP();
      oos.writeObject(bg);
      oos.writeObject(bp);

      KeyPairGenerator kpg = KeyPairGenerator.getInstance("DH");
      kpg.initialize(1024);
      KeyPair kpa = (KeyPair) ois.readObject();
      KeyAgreement dh = KeyAgreement.getInstance("DH");
      KeyPair kp = kpg.generateKeyPair();

      oos.writeObject(kp);

      dh.init(kp.getPrivate());
      Key pk = dh.doPhase(kpa.getPublic(), true);

      MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
      byte[] rawbits = sha256.digest(dh.generateSecret());

      Cipher c = Cipher.getInstance(CIPHER_MODE);
      SecretKey key = new SecretKeySpec(rawbits, 0, 16, "AES");
      byte ivbits[] = (byte[]) ois.readObject();
      IvParameterSpec iv = new IvParameterSpec(ivbits);
      c.init(Cipher.DECRYPT_MODE, key, iv);

      Mac m = Mac.getInstance("HmacSHA1");
      SecretKey mackey = new SecretKeySpec(rawbits, 16, 16, "HmacSHA1");
      m.init(mackey);

      byte ciphertext[], cleartext[], mac[];
      try {
        while (true) {
          ciphertext = (byte[]) ois.readObject();
          mac = (byte[]) ois.readObject();
          if (Arrays.equals(mac, m.doFinal(ciphertext))) {
            cleartext = c.update(ciphertext);
            System.out.println(ct + " : " + new String(cleartext, "UTF-8"));
          } else {
            // System.exit(1);
            System.out.println(ct + "error");
          }
        }
      } catch (EOFException e) {
        cleartext = c.doFinal();
        System.out.println(ct + " : " + new String(cleartext, "UTF-8"));
        System.out.println("[" + ct + "]");
      } finally {
        if (ois != null) ois.close();
        if (oos != null) oos.close();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Exemple #6
0
 public synchronized void sendClientData(String name, ObjectOutputStream out) throws IOException {
   for (ClientData cd : clientList)
     if (cd.getName().equals(name)) {
       out.writeObject(cd);
       return;
     }
 }
  public void run() {
    boolean gotByePacket = false;

    try {
      /* stream to read from client */
      ObjectInputStream fromClient = new ObjectInputStream(socket.getInputStream());
      Packet packetFromClient;

      /* stream to write back to client */
      ObjectOutputStream toClient = new ObjectOutputStream(socket.getOutputStream());

      // writer to the disk
      // String file = "list";

      // while (( packetFromClient = (Packet) fromClient.readObject()) != null) {
      /* create a packet to send reply back to client */

      packetFromClient = (Packet) fromClient.readObject();
      Packet packetToClient = new Packet();
      packetToClient.type = Packet.LOOKUP_REPLY;
      packetToClient.data = new ArrayList<String>();

      if (packetFromClient.type == Packet.LOOKUP_REQUEST) {
        // called by client
        System.out.println("Request from Client:" + packetFromClient.type);

        packetToClient.type = Packet.LOOKUP_REPLY;
        long start = packetFromClient.start;
        long length = packetFromClient.length;

        if (start > dict.size()) {
          // set the error field, return
          packetToClient.error_code = Packet.ERROR_OUT_OF_RANGE;
        } else {
          for (int i = (int) start; i < start + length && i < dict.size(); i++) {
            packetToClient.data.add(dict.get(i));
          }
        }

        toClient.writeObject(packetToClient);
        // continue;
      }

      // }

      /* cleanup when client exits */
      fromClient.close();
      toClient.close();
      socket.close();

      // close the filehandle

    } catch (IOException e) {
      if (!gotByePacket) {
        e.printStackTrace();
      }
    } catch (ClassNotFoundException e) {
      if (!gotByePacket) e.printStackTrace();
    }
  }
Exemple #8
0
 public static void main(String[] args) {
   String str;
   Socket sock = null;
   ObjectOutputStream writer = null;
   Scanner kb = new Scanner(System.in);
   try {
     sock = new Socket("127.0.0.1", 4445);
   } catch (IOException e) {
     System.out.println("Could not connect.");
     System.exit(-1);
   }
   try {
     writer = new ObjectOutputStream(sock.getOutputStream());
   } catch (IOException e) {
     System.out.println("Could not create write object.");
     System.exit(-1);
   }
   str = kb.nextLine();
   try {
     writer.writeObject(str);
     writer.flush();
   } catch (IOException e) {
     System.out.println("Could not write to buffer");
     System.exit(-1);
   }
   try {
     sock.close();
   } catch (IOException e) {
     System.out.println("Could not close connection.");
     System.exit(-1);
   }
   System.out.println("Wrote and exited successfully");
 }
 public void sendObj(Object obj) {
   try {
     objOut.writeObject(obj);
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
 private TaskObjectsExecutionResults runObject(TaskObjectsExecutionRequest obj)
     throws IOException, PDBatchTaskExecutorException {
   Object res = null;
   try {
     setAvailability(false);
     _oos.writeObject(obj);
     _oos.flush();
     res = _ois.readObject();
     setAvailability(true);
   } catch (IOException e) { // worker closed connection
     processException(e);
     throw e;
   } catch (ClassNotFoundException e) {
     processException(e);
     throw new IOException("stream has failed");
   }
   if (res instanceof TaskObjectsExecutionResults) {
     _isPrevRunSuccess = true;
     return (TaskObjectsExecutionResults) res;
   } else {
     PDBatchTaskExecutorException e =
         new PDBatchTaskExecutorException("worker failed to run tasks");
     if (_isPrevRunSuccess == false && !sameAsPrevFailedJob(obj._tasks)) {
       processException(e); // twice a loser, kick worker out
     }
     _isPrevRunSuccess = false;
     _prevFailedBatch = obj._tasks;
     throw e;
   }
 }
 void sendMessage(ChatMessage msg) {
   try {
     sOutput.writeObject(msg);
   } catch (IOException e) {
     display("Exception writing to server: " + e);
   }
 }
  public boolean start() {
    try {
      socket = new Socket(server, port);
    } catch (Exception ec) {
      display("Error connectiong to server:" + ec);
      return false;
    }
    String msg = "Connection accepted " + socket.getInetAddress() + ":" + socket.getPort();
    display(msg);
    try {
      sInput = new ObjectInputStream(socket.getInputStream());
      sOutput = new ObjectOutputStream(socket.getOutputStream());
    } catch (IOException eIO) {
      display("Exception creating new Input/output Streams: " + eIO);
      return false;
    }
    new ListenFromServer().start();
    try {
      sOutput.writeObject(username);
    } catch (IOException eIO) {
      display("Exception doing login : " + eIO);
      disconnect();
      return false;
    }

    return true;
  }
Exemple #13
0
 public void sendOutput(Object obj) {
   try {
     oos.writeObject(obj);
     oos.flush();
   } catch (IOException e) {
     System.out.println(e.getMessage());
   }
 }
Exemple #14
0
 void send(file x) {
   try {
     oout.writeObject(x);
     oout.flush();
   } catch (IOException ex) {
     ex.printStackTrace();
   }
 }
Exemple #15
0
 // send a message to the output stream
 void sendMessage(String msg) {
   try {
     out.writeObject(msg);
     out.flush();
     System.out.println("Send message: " + msg);
   } catch (IOException ioException) {
     ioException.printStackTrace();
   }
 }
Exemple #16
0
 // Utility methods
 // Send message to client
 private void sendMessage(String message) {
   try {
     output.writeObject("KELVIN: " + message);
     output.flush();
     showMessage("\nKELVIN: " + message);
   } catch (IOException ioException) {
     chatWindow.append("\n ERROR: CANNOT SEND MESSAGE! \n");
   }
 }
 private void secondChance(RRObject obj) throws ClassNotFoundException, IOException {
   try {
     obj.runProtocol(_srv, _ois, _oos);
   } catch (PDBatchTaskExecutorException e2) {
     utils.Messenger.getInstance()
         .msg(
             "PDBTEC2ListenerThread.run(): sending NoWorkerAvailableResponse() to client...", 1);
     // e.printStackTrace();
     _oos.writeObject(new NoWorkerAvailableResponse(((TaskObjectsExecutionRequest) obj)._tasks));
     _oos.flush();
   } catch (IOException e2) {
     utils.Messenger.getInstance()
         .msg("PDBTEC2ListenerThread.run(): sending FailedReply to client...", 1);
     // e.printStackTrace();
     _oos.writeObject(new FailedReply());
     _oos.flush();
   }
 }
  // send a message to the output stream
  void SendChunk(int chunkNum) {
    try {
      // Send the chunk number that will follow
      outUp.writeObject(chunkNum + "");
      outUp.flush();

      // Send the chunk
      if (chunkNum != -1) {
        byte[] fileContents = Files.readAllBytes(availableChunks[chunkNum].toPath());
        outUp.writeObject(fileContents);
        outUp.flush();
        System.out.println("Sent chunk " + chunkNum + " to Client");
      }

    } catch (IOException ioException) {
      ioException.printStackTrace();
    }
  }
 public void sendMessage(ObjectExchange data) throws IOException {
   synchronized (this) {
     if (writer != null && !socket.isClosed()) {
       //  data.friend_id  =   transactionId;
       writer.writeObject(data);
       writer.flush();
     }
   }
 }
  void returnnull(ObjectOutputStream oos) {
    if (oos != null)
      try {
        oos.writeObject(null);
        oos.flush();
      } catch (IOException ex1) {

      }
  }
Exemple #21
0
 void send(GameInfo gameInfo) {
   if (out == null) return;
   try {
     out.reset();
     out.writeObject(gameInfo);
     out.flush();
   } catch (Exception e) {
     ctrl.serverError("GameInfo Send error!");
   }
 }
  public static int sizeInBytes(Object obj) throws IOException {
    ByteArrayOutputStream byteObject = new ByteArrayOutputStream();
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteObject);
    objectOutputStream.writeObject(obj);
    objectOutputStream.flush();
    objectOutputStream.close();
    byteObject.close();

    return byteObject.toByteArray().length;
  }
Exemple #23
0
 /*
  * Write a String to the Client output stream
  */
 private boolean writeMsg(ChatMessage cm) {
   // if Client is still connected send the message to it
   if (!socket.isConnected()) {
     close();
     return false;
   }
   // write the message to the stream
   try {
     boolean sendChatMessage = cm.getType() == ChatMessage.ESTABLISHCONNECTION;
     boolean sendMediaFileMessage = cm.getType() == ChatMessage.ESTABLISHCONNECTIONANDPLAY;
     if (sendChatMessage || sendMediaFileMessage) sOutput.writeObject(cm);
     else sOutput.writeObject(cm.getMessage());
   }
   // if an error occurs, do not abort just inform the user
   catch (IOException e) {
     display("Error sending message to " + username);
     display(e.toString());
   }
   return true;
 }
  public boolean sendMessage(Message messageToSend) {

    try {
      out.writeObject(messageToSend);
    } catch (IOException ioe) {
      System.out.println("Could not write to socket: " + socket.getLocalPort());
      return false;
    }

    return true;
  }
 /**
  * sends a message to the server, and to the other clients
  *
  * @param message: message to be sent
  */
 public void sendMessage(String message) {
   try {
     System.out.println("Sending a message..." + message);
     toChatServer.writeObject(new String(message));
     toChatServer.flush();
   } catch (IOException e) {
     System.out.println("IOException in sendMessage");
     System.err.println(e);
     System.exit(1);
   }
 }
  /**
   * update() is customized so that the servlets can interact with it
   *
   * @return a list of available model names from the server
   */
  public void upload(List_entity dr) {
    String strInput = "";
    String serverResponse = "";

    try {
      //					ObjectOutputStream outStream = new ObjectOutputStream(new
      // BufferedOutputStream(sock.getOutputStream()));
      //					outStream.writeObject(dr);
      //					outStream.flush();
      Log.e("DefaultSocketClient", "inside try in upload() of default socket client..");

      Object msg = "upload\n";

      ObjectOutputStream sendmsgToServer = new ObjectOutputStream(sock.getOutputStream());
      sendmsgToServer.writeObject(msg);

      Log.e("DefaultSocketClient", "name of the list that is passed " + dr.getListName());

      //				ObjectOutputStream sendToServer = new ObjectOutputStream(sock.getOutputStream());
      sendmsgToServer.writeObject(dr);
      sendmsgToServer.flush();

      ObjectInputStream receiveFromServer = new ObjectInputStream(sock.getInputStream());
      List_entity le = (List_entity) receiveFromServer.readObject();
      Log.e("DefaultSocketClient", "success.. got the list entity " + le.getListName());

      //					serverResponse = socketReader.readLine();
      //					System.out.println("serverResponse :"+serverResponse);
      //					serverResponse = socketReader.readLine();
      //					System.out.println("Available models from server :"+serverResponse);
      //                sendmsgToServer.close();
      //                receiveFromServer.close();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } finally {

    }
  }
Exemple #27
0
  public void mouseClicked(MouseEvent e) {
    /*can = false;
    boolean f = true;
    for (int i = 0; i < 8; i++)
    {
    	for (int j = 0; j < 8; j++)
    	if (cell[i][j] == e.getSource())
    	{
    		int judege = Clicked(cell[i][j]);
    		f = false;
    		break;
    	}
    	if (!f) break;
    }*/

    boolean flage = CheckAll();
    if (flage) {
      can = false;
      if (kind.equals("" + turn)) {
        ChessBoard cel = (ChessBoard) (e.getSource());
        int judge = Clicked(cel);
        if (judge == 1) {
          try {
            System.out.println("发送前:" + cell[3][5].taken);
            out66.writeObject("落子" + turn);
            out66.flush();
            out66.writeObject(stateList.get(stateList.size() - 1));
            out66.flush();
            out66.writeObject(takenList.get(takenList.size() - 1));
            out66.flush();
          } catch (IOException e1) {
            e1.printStackTrace();
          }
        }
      } else {
        JOptionPane.showMessageDialog(null, "请确定您的身份,您此时不能落子");
      }
    } else CheckAtTheEnd();
  }
Exemple #28
0
  private void send(Socket canal, Mensaje msg) {

    ObjectOutputStream salidaDatos;
    try {

      if (canal == null) canal = this.conexion;
      salidaDatos = new ObjectOutputStream(canal.getOutputStream());
      salidaDatos.writeObject(msg);

    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  /**
   * Sends the specified file to the client. File must exist or client and server threads will hang
   * indefinitely. Generates a session key to encrypt the file over transfer; session key is
   * encrypted using the client's public (asymmetric) key.
   *
   * @param aFile The name or path of the file to send.
   * @throws IOException Error reading from socket.
   */
  private void sendFile(String aFile) throws IOException {
    try {
      // get client public key
      ObjectInputStream clientPubIn = new ObjectInputStream(connectedSocket.getInputStream());
      PublicKey clientPublicKey = (PublicKey) clientPubIn.readObject();

      // generate key string and send to client using their public key encrypted with RSA
      // (asymmetric)
      String keyString = generateKeyString();
      Cipher keyCipher = Cipher.getInstance("RSA");
      keyCipher.init(Cipher.ENCRYPT_MODE, clientPublicKey);
      SealedObject sealedKeyString = new SealedObject(keyString, keyCipher);
      ObjectOutputStream testOut = new ObjectOutputStream(outToClient);
      testOut.writeObject(sealedKeyString);
      testOut.flush();

      // generate key spec from keyString
      SecretKeySpec keySpec = new SecretKeySpec(keyString.getBytes(), "DES");

      // set up encryption
      Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
      cipher.init(Cipher.ENCRYPT_MODE, keySpec);
      CipherOutputStream cipherOut = new CipherOutputStream(outToClient, cipher);

      // send file
      byte[] fileBuffer = new byte[BUFFER_SIZE];
      InputStream fileReader = new BufferedInputStream(new FileInputStream(aFile));
      int bytesRead;
      while ((bytesRead = fileReader.read(fileBuffer)) != EOF) {
        cipherOut.write(fileBuffer, 0, bytesRead);
      }
      cipherOut.flush();
      cipherOut.close();
      disconnect();
    } catch (NoSuchPaddingException nspe) {
      System.out.println("No such padding.");
    } catch (NoSuchAlgorithmException nsae) {
      System.out.println("Invalid algorithm entered");
    } catch (ClassNotFoundException cnfe) {
      System.out.println("Class not found.");
    } catch (InvalidKeyException ike) {
      System.out.println("Invalid key used for file encryption.");
    } catch (FileNotFoundException fnfe) {
      System.out.println("Invalid file entered.");
      return;
    } catch (IllegalBlockSizeException ibse) {
      System.out.println("Illegal block size used for encryption.");
    }
  }
Exemple #30
0
  /** DOCUMENT ME! */
  public void saveRaids() {
    try {
      // setup a stream to a physical file on the filesystem
      FileOutputStream outStream = new FileOutputStream(REPO);

      // attach a stream capable of writing objects to the stream that is connected to the file
      ObjectOutputStream objStream = new ObjectOutputStream(outStream);
      objStream.writeObject(raids);
      objStream.flush();
      objStream.close();
    } catch (IOException e) {
      System.err.println("Things not going as planned.");
      e.printStackTrace();
    } // catch
  }