简体   繁体   English

通过套接字发送文件

[英]Sending Files Over Sockets

Is there a way to send a file over sockets in Java? 有没有办法在Java中通过套接字发送文件? If so how? 如果可以,怎么办? If not, how does one go around sending a file from one computer to another using java? 如果没有,如何使用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... 也就是说,有多种方法可以将文件从一台计算机复制到另一台计算机(使用Java),包括复制到共享文件系统,通过ftp传输文件,将文件http发布到网络服务器...

Client-Server architecture is most suitable to achieve what you want. 客户端-服务器体系结构最适合实现您想要的。

Start FileServer on the first computer and run FileClient on the second. 在第一台计算机上启动FileServer ,在第二台计算机上运行FileClient

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. 而不是使用专有协议构建自己的文件服务器和客户端,您可以在自己的Java应用程序中将ftp-server嵌入服务器端并将ftp客户端嵌入客户端。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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