• TCP通信中文件上传多线程方法


    文件上传多线程方法

    创建一个Upload类,继承Runnable接口,并将Socket封装起来,构造方法有参构造和无参构造,再创建一个run方法,

    public class UPload implements Runnable {
        private Socket socket;
        
        public UPload() {
            super();
        }
        public UPload(Socket socket) {
            super();
            this.socket = socket;
        }
        public void run() {        
            try {
                //明确数据源
                InputStream in = socket.getInputStream();
                //明确目的地
                File file=new File("E:\io1127\picture");
                //如果文件不存在
                if(!file.exists()){
                    //那就创建文件
                    file.mkdirs();
                }
                //明确文件名
                String filename="oracle"+System.currentTimeMillis()+new Random().nextInt(9999)+".jpg";
                //明确目的地
                FileOutputStream fos=new FileOutputStream(file+File.separator+filename);
                //开始复制
                byte[] bytes=new byte[1024];
                int len=0;
                while((len=in.read(bytes))!=-1){
                    fos.write(bytes, 0, len);
                }
                //回复客户端
                //获取字节输出流
                OutputStream out=socket.getOutputStream();
                //发送内容
                out.write("收到".getBytes());    
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public class Demo01 {
        public static void main(String[] args) throws IOException {
            //创建服务器对象,明确端口号
            ServerSocket server=new ServerSocket(8888);
            while(true){
                //与客户端连接
                Socket socket=server.accept();
                //创建线程明确线程任务并开启线程
                new Thread(new UPload(socket)).start();            
            }
    }

    客户端:

    public class TCPClient {
        //客户端
        public static void main(String[] args) throws UnknownHostException, IOException {
            // 创建客户端对象,明确服务器端的ip和端口号
         //此时只需要接入同一个网络中,并设置服务器IP地址,就可以上传文件了
    Socket socket=new Socket("127.0.0.1",8888); //明确数据源 FileInputStream fis=new FileInputStream("E:\io1127\a.jpg"); //明确目的地 OutputStream out=socket.getOutputStream(); int len=0; byte[] bytes=new byte[1024]; //开始复制 while((len=fis.read(bytes))!=-1){ out.write(bytes,0,len); } //告知服务器端结束,别读了 socket.shutdownOutput(); //接收服务器端的回复 //获取字节输入流 InputStream in=socket.getInputStream(); len=in.read(bytes); System.out.println("服务器端回复:"+new String(bytes,0,len)); //释放资源 socket.close(); } }

    上传文件只需要执行客户端就可以,可以同时多个客户端上传文件

  • 相关阅读:
    《DSP using MATLAB》Problem 8.42
    《DSP using MATLAB》Problem 8.41
    《DSP using MATLAB》Problem 8.40
    《DSP using MATLAB》Problem 8.39
    IIR滤波器数字频带转换
    《DSP using MATLAB》Problem 8.38
    《DSP using MATLAB》Problem 8.37
    线性化①
    (七)根轨迹①
    (六)非零初始条件下的传递函数
  • 原文地址:https://www.cnblogs.com/xinzong/p/14478194.html
Copyright © 2020-2023  润新知