简体   繁体   中英

Sending Files Over Sockets

Is there a way to send a file over sockets in Java? If so how? If not, how does one go around sending a file from one computer to another using java?

you open up a socket connection and copy the file bytes into the socket and read the bytes from the other end of the socket. the same way that you send any stream through a socket connection. that said, there's any number of ways to copy a file from one computer to another (using java), including copying to a shared filesystem, ftping the file, http posting the file to a webserver...

Client-Server architecture is most suitable to achieve what you want.

Start FileServer on the first computer and run FileClient on the second.

Sending files over socket.

import java.io.BufferedInputStream;



import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.OutputStream;

import java.net.ServerSocket;

import java.net.Socket;

public class Main
 {

 public static void main(String[] args) throws IOException {

 ServerSocket servsock = new ServerSocket(123456);

File myFile = new File("s.pdf");

while (true)
 {

  Socket sock = servsock.accept();

   byte[] mybytearray = new byte[(int) myFile.length()];

   BufferedInputStream bis = new BufferedInputStream(new FileInputStream(myFile));

  bis.read(mybytearray, 0, mybytearray.length);

   OutputStream os = sock.getOutputStream();

   os.write(mybytearray, 0, mybytearray.length);

     os.flush();

    sock.close();

  }

 }

}

The client module


import java.io.BufferedOutputStream;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.net.Socket;

public class Main {

public static void main(String[] argv) throws Exception
 {

 Socket sock = new Socket("127.0.0.1", 123456);

 byte[] mybytearray = new byte[1024];

 InputStream is = sock.getInputStream();

 FileOutputStream fos = new FileOutputStream("s.pdf");

  BufferedOutputStream bos = new BufferedOutputStream(fos);

   int bytesRead = is.read(mybytearray, 0, mybytearray.length);

 bos.write(mybytearray, 0, bytesRead);

   bos.close();

   sock.close();

  }

}

If your primary attention lies on sending files from one computer to another. And not on building your own file server and client using a proprietary protocol, you can embed an ftp-server at the server side and an ftp client at the client side within your own java applications.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM