Socket connections

Asked

Viewed 85 times

0

I’m trying to do a project where I transfer a file. I’m having trouble accepting the client’s connection. As I am trying to do in different packages the Talya class starts the server connection on line 21, but only then I start the client and then the java.null error..

How to open the server connection and accept in the client if they are in different classes?

code:

package servidor;
import java.io.BufferedInputStream;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;



@SuppressWarnings("unused")
public class Servidor {
    private ServerSocket socketServidor;
    private Socket socketConexao;
    private int porta;

    public Servidor(int porta) {
        this.porta = porta;
    }
    public void iniciaConexaoServidor() {

        try {
            this.socketServidor = new ServerSocket(this.porta);
        } catch (IOException e) {
            System.out.println("Não conseguiu iniciar o socket do servidor");
            e.printStackTrace();
        }
        try {
            this.socketConexao = socketServidor.accept();
        } catch (IOException e) {
            System.out.println("Não conseguiu aceitar a conexao com o cliente.");
            e.printStackTrace();
        }
    }
    public void enviarArquivo(String diretorio) throws Exception {
        File arquivo = new File(diretorio);
        FileInputStream fis = new FileInputStream(arquivo);
        BufferedInputStream bis = new BufferedInputStream(fis);
        OutputStream os = this.socketConexao.getOutputStream();

        byte[] conteudo;
        long fileLength = arquivo.length();
        long current = 0;

        while(current!=fileLength){ 
            int size = 10000;
            if(fileLength - current >= size)
                current += size;    
            else{
                size = (int)(fileLength - current); 
                current = fileLength;
            } 
            conteudo = new byte[size]; 
            bis.read(conteudo, 0, size); 
            os.write(conteudo);
            System.out.println("Mandando arquivo ... "+(current*100)/fileLength+"% completo!");
        }   

        os.flush(); 
        this.socketConexao.close();
        this.socketServidor.close();
        bis.close();
        System.out.println("Arquivo enviado com sucesso!");
    }
}

package Cliente;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;

public class Cliente {
    private Socket socketCliente;
    int porta;
    String address;
    public Cliente(int porta, String address) {
        this.porta=porta;
        this.address=address;
    }
    public void iniciarConexaoCliente() throws Exception {
        this.socketCliente = new Socket(address, porta);
    }
    public void transferenciaArquivo(String diretorio) throws IOException {
        byte[] conteudo = new byte[10000];

        FileOutputStream fos = new FileOutputStream(diretorio);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        InputStream is = socketCliente.getInputStream();

        int bytesRead = 0;

        while((bytesRead=is.read(conteudo))!=-1) {
            bos.write(conteudo, 0, bytesRead);
        }
        bos.flush();
        socketCliente.close();

        System.out.println("Arquivo recebido!");
    }

}
import Cliente.Cliente;
import servidor.Servidor;

import java.io.IOException;
import java.util.Scanner;
@SuppressWarnings("unused")
public class Talya {

    public static void main(String[] args) {
        String adress; //192.168.25.9
        int porta;
        Scanner in = new Scanner(System.in);
        Scanner str = new Scanner(System.in);
        System.out.println("endereço ip: ");
        adress = str.nextLine();
        System.out.println("porta: ");
        porta = in.nextInt();

        Cliente cliente = new Cliente(porta, adress);
        Servidor servidor = new Servidor(porta);
        servidor.iniciaConexaoServidor();
        try {
            cliente.iniciarConexaoCliente();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String diretorioServidor = "C:\\Users\\ange4\\eclipse-workspace\\ProjetoComunicacao\\TesteMusic.rar";
        try {
            servidor.enviarArquivo(diretorioServidor);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String diretorioCliente = "C:\\Users\\ange4\\eclipse-workspace\\ProjetoComunicacao\\TesteMusic2.rar";
        try {
            cliente.transferenciaArquivo(diretorioCliente);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }



    }

}
  • I copied your code and put it to run, but the line this.socketConexao = socketServidor.Accept(); locks the system. Try putting this line of the Talya class to run on a separate thread: server.startServicer(); and see what happens.

  • 2

    Possible duplicate of Error sending files via Java Socket

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.