在没有服务器的情况下在客户端之间发送文件

时间:2018-12-28 23:59:41

标签: java sockets tcp

我正在努力使2个客户端可以彼此发送文件,而无需服务器来调解文件。反正有这样做吗?

我尝试在2个客户端之间创建套接字连接,但是没有用。

编辑:添加了发送代码

这是用于发送文件的:

public void sendFile(File file) {

    Message message = new Message(Message.Action.REQUEST_FILE);
    message.setText(file.getName());
    message.setUsername(model.getUsername());

    try {

        ServerSocket receiver = new ServerSocket(9002);
        byte []buffer = new byte[(int)file.length()];
        OutputStream out = null;
        Socket s = null;

        s = receiver.accept();
        System.out.println("Aceite conneccao de: " + s);
        FileInputStream fis = new FileInputStream(file);
        BufferedInputStream in = new BufferedInputStream(fis);
        in.read(buffer, 0, buffer.length);
        out = s.getOutputStream();
        System.out.println("A enviar o ficheiro!");


        out.write(buffer, 0, buffer.length);
        out.flush();

        out.close();
        in.close();
        s.close();

        System.out.println("Finished Sending");
    } catch (Exception ex) {
        System.exit(0);
    }
}

EDIT_2:添加了用于接收的代码

public void fileAccepted(String host) { //Host = IP or localhost
    /**
     * Create connection with client and send the file.
     */

    Thread files = new Thread();

    while(!files.isInterrupted()){

        try{
            byte []buffer = new byte[999999999];
            Socket recebe = new Socket(host, 9002);
            InputStream is = recebe.getInputStream();

        }catch(UnknownHostException e){
            System.out.println("Unknown Host" + e);
        }catch(IOException e){
            System.out.println("Error Socket" + e);
        };



    }

}

我希望这2个客户端能够在没有服务器中介的情况下互相发送文件。

0 个答案:

没有答案
相关问题