Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.DataInputStream;
- import java.io.DataOutputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.OutputStream;
- import java.net.Socket;
- import java.util.Scanner;
- public class Client implements Runnable {
- private Socket socket;
- private DataOutputStream dout;
- private DataInputStream din;
- public Client(String host, int port) {
- try {
- socket = new Socket(host, port);
- System.out.println("Connected to " + socket);
- din = new DataInputStream(socket.getInputStream());
- dout = new DataOutputStream(socket.getOutputStream());
- new Thread(this).start();
- } catch (IOException ioe) {
- System.out.println(ioe);
- }
- }
- private void sendCommand(String command) {
- try {
- dout.writeUTF(command);
- } catch (IOException ioe) {
- System.out.println(ioe);
- }
- }
- public void run() {
- try {
- Scanner scanner = new Scanner(System.in);
- String command;
- while (true) {
- System.out.print(">");
- command = scanner.nextLine();
- if ( command.toLowerCase().equals("exit") ) {
- System.out.println("Terminating...");
- scanner.close();
- System.exit(0);
- } else {
- sendCommand(command);
- }
- if ( command.equals("ls") ) {
- // Get the list of files in the Directory from the server
- int size = din.read();
- for (int i = 0; i < size; i++) {
- System.out.println(din.readUTF());
- }
- } else if ( command.substring(0, 2).equals("dl") ) {
- // Download the file from the server
- System.out.println("Downloading " + command.substring(3));
- long size = din.readLong();
- System.out.println("File size: " + size);
- byte[] buffer = new byte[(int) size];
- OutputStream output = new FileOutputStream(command.substring(3));
- int bytesRead = 0;
- while(size > 0 && (bytesRead = din.read(buffer, 0, (int)Math.min(buffer.length, size))) != -1) {
- output.write(buffer, 0, bytesRead);
- size -= bytesRead;
- }
- output.close();
- }
- }
- } catch (IOException ioe) {
- System.out.println(ioe);
- }
- }
- public static void main(String[] args) {
- new Client("localhost", 8585);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement