Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedInputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.OutputStream;
- import java.net.InetAddress;
- import java.net.ServerSocket;
- import java.net.Socket;
- public class Servidor {
- public static void main(String[] args) throws Exception {
- //inicializa o servidor
- ServerSocket ssock = new ServerSocket(5000);
- //aceita conexao
- Socket socket = ssock.accept();
- //The InetAddress specification
- InetAddress IA = InetAddress.getByName("localhost");
- //especifica o arquivo
- File file = new File("TesteMusic.rar");
- // transforma o arquio em um formao que pode ser lido(stream de bytes)
- FileInputStream fis = new FileInputStream(file);
- // encapsula o fis para bis para aumentar a velocidade de transferencia
- BufferedInputStream bis = new BufferedInputStream(fis);
- //Pega o output socket para mandar para o cliente
- OutputStream os = socket.getOutputStream();
- //Inicializo o array de bytes
- byte[] contents;
- // tamanho do arquivo
- long fileLength = file.length();
- // long auxiliar para ficar vendo onde esta no arquivo
- long current = 0;
- //loop para converter arquivo para array de bytes
- while(current!=fileLength){
- // meu buffer d tamanho 10000
- int size = 10000;
- // enquanto n chega na ultima parte incrementa current
- if(fileLength - current >= size)
- current += size;
- else{
- // qnd chega na ultima parte, verfica qnt falta e coloca em size
- size = (int)(fileLength - current);
- current = fileLength;
- }
- contents = new byte[size];
- bis.read(contents, 0, size);
- os.write(contents);
- System.out.println("Sending file ... "+(current*100)/fileLength+"% complete!");
- }
- os.flush();
- //File transfer done. Close the socket connection!
- socket.close();
- ssock.close();
- bis.close();
- System.out.println("File sent succesfully!");
- }
- }
- import java.io.BufferedOutputStream;
- import java.io.FileOutputStream;
- import java.io.InputStream;
- import java.net.InetAddress;
- import java.net.Socket;
- public class Cliente {
- public static void main(String[] args) throws Exception{
- //Initialize socket
- Socket socket = new Socket(InetAddress.getByName("localhost"), 5000);
- byte[] contents = new byte[10000];
- //Initialize the FileOutputStream to the output file's full path.
- FileOutputStream fos = new FileOutputStream("TesteMusic2.rar");
- BufferedOutputStream bos = new BufferedOutputStream(fos);
- InputStream is = socket.getInputStream();
- //No of bytes read in one read() call
- int bytesRead = 0;
- while((bytesRead=is.read(contents))!=-1)
- bos.write(contents, 0, bytesRead);
- bos.flush();
- socket.close();
- System.out.println("File saved successfully!");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement