[Java] An example of using TCP, socket and server socket to transfer a file

The simulation process is: A sends a file to B.
A is the sender and B is the receiver.

Use tcp sockets.

used:

ServerSocket ss = new ServerSocket(int 端口号);//接收端
Socket s = ss.accept();//接收端
Socket s=new Socket(String IP地址, int 端口);//发送端
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(String 文件路径+文件名));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(String 文件路径+文件名));

文件路径格式可以是:
"D:\\....\\....\\文件名"

比特数组:
byte[] buf=new byte[1024];

循环读取
int b;
while((b=bis.read(buf))!=-1){
    
    
    fos.write(buf,0,b);
    fos.flush();
}

Sender A:

BufferedInputStream reads a file locally through the new FileInputStream() method. The FileOutputStream instance in BufferedOutputStream is obtained through the s.getOutputStream() method, and is to be sent to a host in the network.

Receiver B:

Contrary to the sending end, or corresponding.
The FileInputStream in BufferedInputStream is obtained through s.getInputStream() and obtained from the network, and BufferedOutputStream writes the file to the local path through the new FileOutputStream() method.

Code:
sender:

try {
    
    
            Socket s=new Socket("127.0.0.1",端口);
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\file\\tee"));
            BufferedOutputStream fos = new BufferedOutputStream(s.getOutputStream());

            byte[] buf=new byte[1024];
            int b;
            while((b=bis.read(buf))!=-1){
    
    
                fos.write(buf,0,b);
                fos.flush();
            }

            fos.close();
			bis.close();
			
        } catch (IOException exception) {
    
    
            exception.printStackTrace();
        }

Receiving end:

 try {
    
    

            ServerSocket ss = new ServerSocket(端口);
            Socket s = ss.accept();

            BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
            BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream("D:\\otherfile\\tee"));

            byte[] buf=new byte[1024];
            int b;
            while((b=bis.read(buf))!=-1){
    
    
                fos.write(buf,0,b);
                fos.flush();
            }
            
            fos.close();
            bis.close();

        } catch (IOException exception) {
    
    
            exception.printStackTrace();
        }

Guess you like

Origin blog.csdn.net/qq_43750882/article/details/111287836