Esempio n. 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!");
   }
 }
Esempio n. 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!");
   }
 }
Esempio n. 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!");
   }
 }
Esempio n. 4
0
 public static void startServer() {
   try {
     System.out.println("Starting server...");
     serverSocket = new ServerSocket(7788);
     System.out.println("Server Started... Address: " + serverSocket.getInetAddress());
     while (true) {
       socket = serverSocket.accept();
       for (int i = 0; i < 10; i++) {
         if (user[i] == null) {
           System.out.println("User " + (i + 1) + " connected from " + socket.getInetAddress());
           socket.setTcpNoDelay(false);
           out = new ObjectOutputStream(socket.getOutputStream());
           in = new ObjectInputStream(socket.getInputStream());
           out.writeInt(i);
           out.flush();
           User theUser = new User(out, in, i);
           user[i] = theUser;
           Thread thread = new Thread(user[i]);
           thread.start();
           break;
         }
       }
     }
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Esempio n. 5
0
  public void run() {
    try {
      System.out.println("socked");
      sock = new Socket(ii, pp);
      oout = new ObjectOutputStream(sock.getOutputStream());
      oout.flush();

      oin = new ObjectInputStream(sock.getInputStream());
      System.out.println("read ");
      rf.setLength(0);
      do {
        System.out.println("read ");
        file f = (file) oin.readObject();
        if (f.length <= 0) break;
        write(f);
      } while (true);
      oout.close();
      oin.close();
      rf.close();
      sock.close();
      xx.ConfirmPopup("Haua file namano shesh!!!");

    } catch (Exception 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;
   }
 }
Esempio n. 7
0
  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();
    }
  }
Esempio n. 8
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
   }
 }
Esempio n. 9
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");
 }
 private void handleKeepAlive() {
   Connection c = null;
   try {
     netCode = ois.readInt();
     c = checkConnectionNetCode();
     if (c != null && c.getState() == Connection.STATE_CONNECTED) {
       oos.writeInt(ACK_KEEP_ALIVE);
       oos.flush();
       System.out.println("->ACK_KEEP_ALIVE"); // $NON-NLS-1$
     } else {
       System.out.println("->NOT_CONNECTED"); // $NON-NLS-1$
       oos.writeInt(NOT_CONNECTED);
       oos.flush();
     }
   } catch (IOException e) {
     System.out.println("handleKeepAlive: " + e.getMessage()); // $NON-NLS-1$
     if (c != null) {
       c.setState(Connection.STATE_DISCONNECTED);
       System.out.println(
           "Connection closed with "
               + c.getRemoteAddress()
               + //$NON-NLS-1$
               ":"
               + c.getRemotePort()); // $NON-NLS-1$
     }
   }
 }
Esempio n. 11
0
  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();
    }
  }
Esempio n. 12
0
 public void sendOutput(Object obj) {
   try {
     oos.writeObject(obj);
     oos.flush();
   } catch (IOException e) {
     System.out.println(e.getMessage());
   }
 }
Esempio n. 13
0
 void send(file x) {
   try {
     oout.writeObject(x);
     oout.flush();
   } catch (IOException ex) {
     ex.printStackTrace();
   }
 }
Esempio n. 14
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();
   }
 }
Esempio n. 15
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");
   }
 }
  void returnnull(ObjectOutputStream oos) {
    if (oos != null)
      try {
        oos.writeObject(null);
        oos.flush();
      } catch (IOException ex1) {

      }
  }
Esempio n. 17
0
 public void sendMessage(ObjectExchange data) throws IOException {
   synchronized (this) {
     if (writer != null && !socket.isClosed()) {
       //  data.friend_id  =   transactionId;
       writer.writeObject(data);
       writer.flush();
     }
   }
 }
  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;
  }
Esempio n. 19
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!");
   }
 }
Esempio n. 20
0
  // Initializes a GameClinet over port to the given host,
  // requesting to join using the given handle
  private GameClient(String host, int port, String handle) throws IOException {
    conn = new Socket(host, port);
    oos = new ObjectOutputStream(conn.getOutputStream());
    oos.flush();
    ois = new ObjectInputStream(conn.getInputStream());

    oos.writeUTF(handle);
    oos.flush();

    runReceiveThread();
  }
 /**
  * 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);
   }
 }
Esempio n. 22
0
  @Override
  public void run() {
    try {
      out = new ObjectOutputStream(csocket.getOutputStream());
      out.flush();
      in = new ObjectInputStream(csocket.getInputStream());

      // Look for chunks
      String currentDir = System.getProperty("user.dir");
      File folder = new File(currentDir + "/src/srcFile");
      File[] listOfFiles = folder.listFiles();
      int fileCount = 0;
      OutputStream os;
      for (int i = 0; i < listOfFiles.length; i++) {
        if (listOfFiles[i].isFile()
            && listOfFiles[i]
                .getName()
                .toLowerCase()
                .contains("chunk")) { // 0 1 10 11 12 13 14 2 20 21 22 23 3 4 5 ....
          fileCount++;
          String chunkName = listOfFiles[i].getName().toString();
          chunkId = chunkName.substring(chunkName.lastIndexOf('.') + 6);

          xPayload(chunkId);
          if ((connTo.equals("2") && Integer.parseInt(chunkId) % noDev == 0)
              || (connTo.equals("3") && (Integer.parseInt(chunkId) - 1) % noDev == 0)
              || (connTo.equals("4") && (Integer.parseInt(chunkId) - 2) % noDev == 0)
              || (connTo.equals("5") && (Integer.parseInt(chunkId) - 3) % noDev == 0)
              || (connTo.equals("6") && (Integer.parseInt(chunkId) - 4) % noDev == 0)) {

            System.out.println(chunkName);
            sendFile(chunkName);
          }
        }
      }

      xPayload("-1");
      System.out.println("All chunks sent.");

    } catch (IOException ioException) {
      ioException.printStackTrace();
    } finally {
      // Close connections
      try {
        in.close();
        out.close();
        csocket.close();
        System.out.println("Thread closed.");
      } catch (IOException ioException) {
        System.out.println("Client " + devId + " disconnected.");
      }
    }
  }
  private synchronized void broadcast(int i) {
    ObjectOutputStream dataOut = null;

    for (Enumeration e = clients.elements(); e.hasMoreElements(); ) {
      dataOut = (ObjectOutputStream) (e.nextElement());
      try {
        dataOut.writeInt(i);
        dataOut.flush();
      } catch (Exception x) {
        System.out.println(x.getMessage() + ": Failed to broadcast to client.");
        clients.removeElement(dataOut);
      }
    }
  }
Esempio n. 24
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();
    }
  }
Esempio n. 25
0
  byte[] messageToBuffer(Message msg) throws Exception {
    ObjectOutputStream out;
    // BufferedOutputStream bos;

    out_stream.reset();
    // bos=new BufferedOutputStream(out_stream);
    out_stream.write(Version.version_id, 0, Version.version_id.length); // write the version
    // bos.write(Version.version_id, 0, Version.version_id.length); // write the version
    out = new ObjectOutputStream(out_stream);
    // out=new ObjectOutputStream(bos);
    msg.writeExternal(out);
    out.flush(); // needed if out buffers its output to out_stream
    return out_stream.toByteArray();
  }
Esempio n. 26
0
  /**
   * 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.");
    }
  }
Esempio n. 27
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
  }
 private PDBTEW2Listener(PDBTExecSingleCltWrkInitSrv srv, Socket s) throws IOException {
   _srv = srv;
   _s = s;
   _ois = new ObjectInputStream(_s.getInputStream());
   _oos = new ObjectOutputStream(_s.getOutputStream());
   _oos.flush();
 }
Esempio n. 29
0
 void sendMessage(ChatMessage msg) {
   try {
     sOutput.writeObject(msg);
   } catch (IOException e) {
     display("Exception writing to server: " + e);
   }
 }
Esempio n. 30
0
 public synchronized void sendClientData(String name, ObjectOutputStream out) throws IOException {
   for (ClientData cd : clientList)
     if (cd.getName().equals(name)) {
       out.writeObject(cd);
       return;
     }
 }