Esempio n. 1
0
  public static void main(String[] argv) {
    String hostName;
    if (argv.length == 0) hostName = "localhost";
    else hostName = argv[0];

    try {
      Socket sock = new Socket(hostName, TIME_PORT);
      ObjectInputStream is = new ObjectInputStream(new BufferedInputStream(sock.getInputStream()));

      // Read and validate the Object
      Object o = is.readObject();
      if (o == null) {
        System.err.println("Read null from server!");
      } else if ((o instanceof Date)) {

        // Valid, so cast to Date, and print
        Date d = (Date) o;
        System.out.println("Server host is " + hostName);
        System.out.println("Time there is " + d.toString());

      } else {
        throw new IllegalArgumentException("Wanted Date, got " + o);
      }
    } catch (ClassNotFoundException e) {
      System.err.println("Wanted date, got INVALID CLASS (" + e + ")");
    } catch (IOException e) {
      System.err.println(e);
    }
  }
  void ReceiveFileChunksFromServer() throws Exception, ClassNotFoundException {
    try {
      if (flagFilename) {
        filename = (String) in.readObject();
        totalChunks = Integer.parseInt((String) in.readObject());
        flagFilename = false;
      }

      if (availableChunks == null) availableChunks = new File[totalChunks];

      if (requiredChunks == null) requiredChunks = new File[totalChunks];

      int partNumber = Integer.parseInt((String) in.readObject());

      File partFile = new File("chunks/" + filename + "." + partNumber);
      byte[] msg = (byte[]) in.readObject();
      Files.write(partFile.toPath(), msg);
      availableChunks[partNumber] = partFile;
      System.out.println("Received chunk " + partNumber);
    } catch (ClassNotFoundException e) {
      flag = true;
    } catch (Exception e) {
      flag = true;
    }
  }
Esempio n. 3
0
  public void run() {
    while (true) {
      try {
        System.out.println("Server name: " + serverSocket.getInetAddress().getHostName());
        System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
        Socket server = serverSocket.accept();
        System.out.println("Just connected to " + server.getRemoteSocketAddress());

        ObjectInputStream objectIn = new ObjectInputStream(server.getInputStream());

        try {
          Recipe rec = (Recipe) objectIn.readObject();
          startHMI(rec, rec.getProductName());

          //				System.out.println("Object Received: width: "+rec.getWidth()+" height:
          // "+rec.getHeight());
        } catch (ClassNotFoundException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }

        DataOutputStream out = new DataOutputStream(server.getOutputStream());
        out.writeUTF(
            "Thank you for connecting to " + server.getLocalSocketAddress() + "\nGoodbye!");
        server.close();
      } catch (SocketTimeoutException s) {
        System.out.println("Socket timed out!");
        break;
      } catch (IOException e) {
        e.printStackTrace();
        break;
      }
    }
  }
Esempio n. 4
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();
    }
  }
Esempio n. 5
0
  /** DOCUMENT ME! */
  public void loadRaids() {
    File f = new File(REPO);

    if (!f.exists()) {
      return;
    }

    FileInputStream fIn = null;
    ObjectInputStream oIn = null;

    try {
      fIn = new FileInputStream(REPO);
      oIn = new ObjectInputStream(fIn);
      // de-serializing object
      raids = (HashMap<String, GregorianCalendar>) oIn.readObject();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } finally {
      try {
        oIn.close();
        fIn.close();
      } catch (IOException e1) {
        e1.printStackTrace();
      }
    }
  }
Esempio n. 6
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. 7
0
  /**
   * * run takes in stream of bytes from client, deserializes it as Cookie, and calls sendResponse
   * to output back to client. If received client object is not an expected class then a
   * ClassNotFoundException is thrown. Socket is then closed when work is done.
   */
  public void run() {
    ObjectInputStream inputObject = null;
    ObjectOutputStream outputObject = null;

    try {
      inputObject =
          new ObjectInputStream(
              socket.getInputStream()); // inputObject used to store stream of bytes from client
      outputObject =
          new ObjectOutputStream(
              socket.getOutputStream()); // outputObject used to send bytes back to client

      try {
        Response responseToClient = new Response(); // Response object to be sent back to client
        Cookie clientCookie;
        clientCookie =
            (Cookie)
                inputObject
                    .readObject(); // deserializes object, casts it as Cookie, and stores it in
                                   // clientCookie
        sendResponse(
            clientCookie,
            responseToClient,
            outputObject); // sendResponse is called to send output to client
      } catch (
          ClassNotFoundException
              exp) { // throws ClassNotFoundException if inputObject cannot be read as Cookie object
        System.out.println("Cannot find class object");
        exp.printStackTrace();
      }
      socket.close(); // close socket to requested server
    } catch (IOException exp) { // throw IOException if inputObject is not of type ObjectInputStream
      System.out.println(exp); // or outputObject is not of type ObjectOutputStream
    }
  }
 @Override
 public void run() {
   isActive = true;
   try {
     serverSocket = new ServerSocket(Utils.getLOCAL_PORT());
     notifyStatusListeners(
         Messages.getInstance()
             .getString(
                 "T_NET_SERVER_LISTENING_ON_PORT",
                 Integer.toString(Utils.getLOCAL_PORT()))); // $NON-NLS-1$
   } catch (IOException e) {
     if (e instanceof BindException) {
       notifyStatusListeners(
           Messages.getInstance()
               .getString(
                   "T_PORT_ALREADY_IN_USE",
                   Integer.toString(Utils.getLOCAL_PORT()))); // $NON-NLS-1$
     } else e.printStackTrace();
     isActive = false;
   }
   while (isActive) {
     try {
       listenSocket = serverSocket.accept();
       ois = new ObjectInputStream(listenSocket.getInputStream());
       oos = new ObjectOutputStream(listenSocket.getOutputStream());
       receivedMessage = ois.readInt();
       System.out.println(messageToString(receivedMessage));
       switch (receivedMessage) {
         case CONNECT:
           handleConnect();
           break;
         case SEND_CODE:
           handleSendCode();
           break;
         case KEEP_ALIVE:
           handleKeepAlive();
           break;
         case DISCONNECT:
           handleDisconnect();
           break;
       }
       ois.close();
       oos.close();
     } catch (IOException e) {
       System.out.println(e.getMessage());
     } finally {
       if (listenSocket != null)
         try {
           listenSocket.close();
         } catch (IOException e) {
           e.printStackTrace();
         }
     }
   }
 }
 public static Object arrayToObject(byte[] b, int offset) {
   try {
     int len = arrayToInteger(b, offset);
     ByteArrayInputStream bais = new ByteArrayInputStream(b, offset + 4, len);
     ObjectInputStream ois = new ObjectInputStream(bais);
     return ois.readObject();
   } catch (IOException e) {
     e.printStackTrace();
     throw new RuntimeException("unable to deserialize packet (io error)", e);
   } catch (ClassNotFoundException e) {
     e.printStackTrace();
     throw new RuntimeException("unable to deserialize packet (class not found)", e);
   }
 }
Esempio n. 10
0
 public List_entity getAllLists() {
   List_entity listentities = new List_entity();
   try {
     out.println("select");
     ObjectInputStream receiveFromServer = new ObjectInputStream(sock.getInputStream());
     List_entity le = (List_entity) receiveFromServer.readObject();
     //            listentities.add(le);
   } catch (IOException e) {
     e.printStackTrace();
   } catch (ClassNotFoundException e) {
     e.printStackTrace();
   }
   return listentities;
 }
Esempio n. 11
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.");
    }
  }
 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;
   }
 }
  /**
   * Constantly reads the client's input stream. Sends all objects that are read to the server. Not
   * to be called.
   */
  public final void run() {
    server.clientConnected(this);

    // This loop reads the input stream and responds to messages
    // from clients
    try {
      // The message from the client
      Object msg;

      while (!readyToStop) {
        // This block waits until it reads a message from the client
        // and then sends it for handling by the server
        msg = input.readObject();
        server.receiveMessageFromClient(msg, this);
      }
    } catch (Exception exception) {
      if (!readyToStop) {
        try {
          closeAll();
        } catch (Exception ex) {
        }

        server.clientException(this, exception);
      }
    }
  }
 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$
     }
   }
 }
 /** Stop talking to the server */
 public void stop() {
   if (socket != null) {
     // Close all the streams and socket
     if (out != null) {
       try {
         out.close();
       } catch (IOException ioe) {
       }
       out = null;
     }
     if (in != null) {
       try {
         in.close();
       } catch (IOException ioe) {
       }
       in = null;
     }
     if (socket != null) {
       try {
         socket.close();
       } catch (IOException ioe) {
       }
       socket = null;
     }
   } else {
     // Already stopped
   }
   // Make sure the right buttons are enabled
   start_button.setEnabled(true);
   stop_button.setEnabled(false);
   setStatus(STATUS_STOPPED);
 }
Esempio n. 16
0
 public void close() {
   try {
     if (streamIn != null) streamIn.close();
     if (streamInObject != null) streamInObject.close();
   } catch (IOException ioe) {
     System.out.println("Error closing input stream: " + ioe);
   }
 }
  private void handleSendCode() {
    Connection c = null;
    GeneticCode code;

    try {
      netCode = ois.readInt();
      c = checkConnectionNetCode();
      if (c != null && c.getState() == Connection.STATE_CONNECTED) {
        oos.writeInt(WAITING_CODE);
        oos.flush();
        System.out.println("->WAITING_CODE"); // $NON-NLS-1$
        code = (GeneticCode) ois.readObject();
        System.out.println("Genetic code"); // $NON-NLS-1$
        oos.writeInt(CODE_RECEIVED);
        oos.flush();
        System.out.println("->CODE_RECEIVED"); // $NON-NLS-1$
        c.getInCorridor().receiveOrganism(code);
      } else {
        System.out.println("->NOT_CONNECTED"); // $NON-NLS-1$
        oos.writeInt(NOT_CONNECTED);
        oos.flush();
      }
    } catch (IOException e) {
      System.out.println("handleSendCode: " + 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$
      }
    } catch (ClassNotFoundException e) {
      System.out.println("handleSendCode: " + 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. 18
0
 public Object getObj() {
   try {
     return objIn.readObject();
   } catch (IOException | ClassNotFoundException e) {
     e.printStackTrace();
   }
   return null;
 }
  public void run() {

    try {
      ObjectInputStream in = new ObjectInputStream(_socket.getInputStream());
      DebugMessage mess = (DebugMessage) in.readObject();
      _ctrl.onMessageRecieved(mess);
      in.close();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        _socket.close();
      } catch (IOException ex) {
        System.err.println("Error closing server socket");
      }
    }
  }
 private void handleConnect() {
   try {
     int program_version = ois.readInt();
     port = ois.readInt();
     address = listenSocket.getInetAddress();
     netCode = ois.readInt();
     Connection c = checkConnectionNetCode();
     if (c != null) {
       oos.writeInt(ALREADY_CONNECTED);
       oos.flush();
       System.out.println("->ALREADY_CONNECTED"); // $NON-NLS-1$
     } else {
       if (isAcceptingConnections()) {
         if (connections.size() < Utils.getMAX_CONNECTIONS()) {
           if (Utils.VERSION == program_version) {
             Connection newConnection = newConnection();
             if (newConnection != null) {
               oos.writeInt(CONNECTED);
               newConnection.setState(Connection.STATE_CONNECTED);
               System.out.println("->CONNECTED"); // $NON-NLS-1$
             } else {
               oos.writeInt(ALREADY_CONNECTED);
               System.out.println("->ALREADY_CONNECTED"); // $NON-NLS-1$
             }
             oos.flush();
           } else {
             oos.writeInt(INCOMPATIBLE_PROGRAM_VERSION);
             oos.flush();
             System.out.println("->INCOMPATIBLE_PROGRAM_VERSION"); // $NON-NLS-1$
           }
         } else {
           oos.writeInt(TOO_MANY_CONNECTIONS);
           oos.flush();
           System.out.println("->TOO_MANY_CONNECTIONS"); // $NON-NLS-1$
         }
       } else {
         oos.writeInt(NOT_ACCEPTING_CONNECTIONS);
         oos.flush();
         System.out.println("->NOT_ACCEPTING_CONNECTIONS"); // $NON-NLS-1$
       }
     }
   } catch (IOException ex) {
     System.out.println(ex.getMessage());
   }
 }
Esempio n. 21
0
  private Mensaje receive(Socket canal) {
    ObjectInputStream entradaDatos;

    try {
      if (canal == null) canal = this.conexion;
      entradaDatos = new ObjectInputStream(canal.getInputStream());
      return (Mensaje) entradaDatos.readObject();

    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return null;
  }
Esempio n. 22
0
 void disconnect() {
   try {
     if (out != null) out.close();
     if (in != null) in.close();
     if (connection != null) connection.close();
   } catch (IOException ex) {
     ctrl.serverError("Error while closing connection with client!");
   }
 }
  void ReceiveFileChunkFromNeighbor() throws Exception, ClassNotFoundException {
    try {
      int chunkNum = Integer.parseInt((String) inDown.readObject());
      if (chunkNum == -1) return;

      byte[] msg = (byte[]) inDown.readObject();

      File chunkFile = new File("chunks/" + filename + "." + chunkNum);
      Files.write(chunkFile.toPath(), msg);

      availableChunks[chunkNum] = chunkFile;
      System.out.println("Received chunk " + chunkNum + " from Client " + dwldNeighbor);
    } catch (ClassNotFoundException e) {
      flag = true;
    } catch (Exception e) {
      flag = true;
    }
  }
Esempio n. 24
0
    // what will run forever
    public void run() {
      // to loop until LOGOUT
      boolean keepGoing = true;
      while (keepGoing) {
        // read a String (which is an object)
        try {
          cm = (ChatMessage) sInput.readObject();
        } catch (IOException e) {
          display(username + " Exception reading Streams: " + e);
          break;
        } catch (ClassNotFoundException e2) {
          break;
        }
        // the messaage part of the ChatMessage
        String message = cm.getMessage();

        // Switch on the type of message receive
        switch (cm.getType()) {
          case ChatMessage.MESSAGE:
            broadcast(username + ": " + message);
            break;
          case ChatMessage.LOGOUT:
            display(username + " disconnected with a LOGOUT message.");
            keepGoing = false;
            break;
          case ChatMessage.WHOISIN:
            writeMsg("List of the users connected at " + sdf.format(new Date()) + "\n");
            // scan al the users connected
            for (int i = 0; i < al.size(); ++i) {
              ClientThread ct = al.get(i);
              writeMsg((i + 1) + ") " + ct.username + " since " + ct.date);
            }
            break;
          case ChatMessage.TO:
            broadcastOnlyOne(username + ": " + message, cm);
            break;
          case ChatMessage.SENDFILE:
            sendFile(username + ": " + message, cm);
            break;
          case ChatMessage.PROCEED:
            proceedSendFile();
            break;
          case ChatMessage.SENDMEDIAFILE:
            String fileList = getFileList();
            writeMsg(new ChatMessage(ChatMessage.SENDMEDIAFILE, fileList));
            break;
          case ChatMessage.ESTABLISHCONNECTIONANDPLAY:
            sendMediaFile(username + ": " + message, cm);
            break;
        }
      }
      // remove myself from the arrayList containing the list of the
      // connected Clients
      remove(id);
      close();
    }
Esempio n. 25
0
 public static void main(String args[]) {
   // declaration section:
   // declare a server socket and a client socket for the server
   // declare an input and an output stream
   ServerSocket echoServer = null;
   String line;
   DataInputStream is;
   PrintStream os;
   Socket clientSocket = null;
   // Try to open a server socket on port 9999
   // Note that we can't choose a port less than 1023 if we are not
   // privileged users (root)
   try {
     echoServer = new ServerSocket(9999);
   } catch (IOException e) {
     System.out.println(e);
   }
   // Create a socket object from the ServerSocket to listen and accept
   // connections.
   // Open input and output streams
   try {
     clientSocket = echoServer.accept();
     is = new DataInputStream(clientSocket.getInputStream());
     os = new PrintStream(clientSocket.getOutputStream());
     // As long as we receive data, echo that data back to the client.
     while (true) {
       ObjectInputStream ois = new ObjectInputStream(is);
       test t = null;
       try {
         t = (test) ois.readObject();
       } catch (ClassNotFoundException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
       }
       System.out.println(t.getS());
       line = is.readLine();
       os.println(line);
     }
   } catch (IOException e) {
     System.out.println(e);
   }
 }
Esempio n. 26
0
 // Close crap after chatting
 private void closeCrap() {
   showMessage("\n Closing connection... \n ");
   ableToType(false);
   try {
     output.close();
     input.close();
     connection.close();
   } catch (IOException ioException) {
     ioException.printStackTrace();
   }
 }
Esempio n. 27
0
 public void close() throws IOException {
   if (in != null) {
     in.close();
   }
   if (out != null) {
     out.close();
   }
   if (socket != null && !socket.isClosed()) {
     socket.close();
   }
 }
Esempio n. 28
0
 void run() {
   try {
     // 1. creating a server socket
     Scanner sc = new Scanner(System.in);
     providerSocket = new ServerSocket(2004, 10);
     // 2. Wait for connection
     System.out.println("Waiting for connection");
     connection = providerSocket.accept();
     System.out.println("Connection received from " + connection.getInetAddress().getHostName());
     // 3. get Input and Output streams
     out = new ObjectOutputStream(connection.getOutputStream());
     out.flush();
     in = new ObjectInputStream(connection.getInputStream());
     sendMessage("Connection successful");
     // 4. The two parts communicate via the input and output streams
     do {
       try {
         message = (String) in.readObject();
         System.out.println("client>" + message);
         if (message.equals("bye")) sendMessage("bye");
         else {
           message = sc.nextLine();
           sendMessage(message);
         }
       } catch (ClassNotFoundException classnot) {
         System.err.println("Data received in unknown format");
       }
     } while (!message.equals("bye"));
   } catch (IOException ioException) {
     ioException.printStackTrace();
   } finally {
     // 4: Closing connection
     try {
       in.close();
       out.close();
       providerSocket.close();
     } catch (IOException ioException) {
       ioException.printStackTrace();
     }
   }
 }
Esempio n. 29
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.");
      }
    }
  }
Esempio n. 30
0
 void run() {
   try {
     server = new ServerSocket(9666, 10);
     System.out.println("Waiting for client");
     client = server.accept();
     System.out.println("Connection received from " + client.getInetAddress().getHostName());
     out = new ObjectOutputStream(client.getOutputStream());
     out.flush();
     in = new ObjectInputStream(client.getInputStream());
     sendMessage("Connection successful");
     int suma = 0, i = 0;
     do {
       try {
         message = (String) in.readObject();
         System.out.println("client: " + message);
         if (message.equals("bye")) sendMessage("bye");
         else {
           suma += Integer.parseInt(message);
           i++;
           if (i == 2) {
             sendMessage(suma % 2 == 0 ? "Parzysta" : "Nieparzysta");
             suma = 0;
           }
         }
       } catch (ClassNotFoundException classnot) {
         classnot.printStackTrace();
       }
     } while (!message.equals("bye"));
   } catch (IOException ioException) {
     ioException.printStackTrace();
   } finally {
     try {
       in.close();
       out.close();
       server.close();
     } catch (IOException ioException) {
       ioException.printStackTrace();
     }
   }
 }