java 网络编程之传输文件(一)

需要建两个类,分别作为服务器(接收文件)和客户端(发送文件)

1.服务器类:

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 服务器-用来接收文件
 */
public class FileServer {
    public static void main(String[] args) {
        //自己的ip地址
        String ip = InetAddress.getLoopbackAddress().getHostAddress();
        int port = 33999;
        ServerSocket ss = null;
        try {
            ss = new ServerSocket(port);
            Socket s = ss.accept();//接收从服务器传来的文件
//            InputStream in;

            //接收的文件以ip地址为名显示
            String cip = s.getRemoteSocketAddress().toString().replace(".", "").replace(":", "") + ".jpg";
            System.out.println(cip);

            BufferedInputStream bis = new BufferedInputStream(s.getInputStream());

            //输出显示接收到的文件
//            File file;
            try {
                FileOutputStream fos = new FileOutputStream("D:/Users/Administrator/Desktop" + cip);
                byte[] buf = new byte[1024];
                int len = -1;
                while ((len = bis.read(buf)) != -1) {
                    fos.write(buf, 0, len);
                }
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

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


    }
}

2.客户端类:

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 客户端-用来发送文件
 */
public class FileClient {
    public static void main(String[] args) {
        String server_ip = "Localhost";//地址是谁,就发给谁,此处设的是本机
        int port = 33999;
        try {
//            ServerSocket ss = new ServerSocket(port);
            Socket s = new Socket(server_ip, port);
            OutputStream os = s.getOutputStream();
            //向服务器发送文件
//            File file;
            FileInputStream fis = new FileInputStream("D:/JavaFiles/Train/bg_gray.jpg");//发送给服务器的文件地址
            //
            byte[] buf = new byte[1024];//每次以1kb传输
            int len = -1;
            while ((len = fis.read(buf)) != -1) {
                os.write(buf, 0, len);

            }
            os.flush();
            os.close();


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

3.运行时,若自己测试(自己给自己传.jpg图片),先运行服务器类,再运行客户端类,成功运行后图片就会显示在服务器类填写的文件路径中.

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

jsonCC

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值