【Java小项目】一个Socket连续传输多个文件

      想给前短时间做的那个山寨QQ加一个传输文件的功能,因为那个山寨QQ每个客户端和服务器端就一个Socket连接用ObjectOutputStream进行通信,现在要加一个DataOutputStream来传输文件,所以先了写这个试验下。


     思路:

             1.在发送DataOutputStream字节流前先发一个Object来通知接受端。

             2.用writeLong通知接收端该文件的长度。

             3.用writeUTF发送文件名称

             4.接受端用接受到的文件长度来跳出读文件的循环

             5.(缺点)接收文件的时候不能在接收Object信息

代码如下

      Server

package com.server;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by ztc on 15-11-16.
 */
public class MyServer extends JFrame implements ActionListener{
    ServerSocket ss=null;
    Socket s=null;

    JFileChooser jfc;
    JButton jb,jb1;
    JTextArea jta;
    ObjectOutputStream oos;
    public static void main(String[] args){
        MyServer ms=new MyServer(8888);
        //ms.SendFile();
    }
    public MyServer(int port) {
        jfc=new JFileChooser();
        jb=new JButton("传输文件");
        jb.addActionListener(this);
        jb1=new JButton("SendObject!");
        jb1.addActionListener(this);
        jta=new JTextArea();
        jta.setEditable(false);
        jta.setAutoscrolls(true);
        this.add(jta,"Center");
        this.add(jb,"South");
        this.add(jb1,"North");

        this.setVisible(true);
        this.setLocation(500,300);
        this.setSize(300,200);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        try {
            ss=new ServerSocket(port);
            System.out.println("Server is running...on"+port);
            s=ss.accept();
            oos=new ObjectOutputStream(s.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    public void SendFile(File f,Object o){
        try {
            oos.writeObject(o);
            oos.flush();

            DataInputStream dis=new DataInputStream(new FileInputStream(f));
            DataOutputStream dos=new DataOutputStream(s.getOutputStream());
            //ObjectOutputStream oos=new ObjectOutputStream(s.getOutputStream());
            //oos.writeObject(f);
            dos.writeLong(f.length());
            dos.writeUTF(f.getName());
            System.out.println("长度:"+f.length());
            int count=-1,sum=0;
            byte[] buffer=new byte[1024*1024];
            while((count=dis.read(buffer))!=-1){
                dos.write(buffer,0,count);
                sum+=count;
                System.out.println("以传输"+sum+"byte");
            }
            System.out.println("发送完毕!");
            dos.flush();

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

    public void SendObject(Object o){
        try {
            oos.writeObject(o);
            oos.flush();
            System.out.println("Sended Object!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource()==jb){
            jfc.setCurrentDirectory(jfc.getCurrentDirectory());
            int result=jfc.showOpenDialog(this);
            File f=jfc.getSelectedFile();
            if(result==0&&f!=null){
                SendFile(f,"File");
            }
        }else if(e.getSource()==jb1){
            SendObject("hello Im Server!");
        }
    }
}

Client

package com.client;

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

/**
 * Created by ztc on 15-11-16.
 */
public class MyClient{
    static Socket s = null;
    public static void main(String[] args) {
        MyClient my=new MyClient("127.0.0.1", 8888);
    }

    public MyClient(String host, int port) {

        try {
            s=new Socket(host,port);
            System.out.println("Data running>>>");
            ObjectInputStream ois=new ObjectInputStream(s.getInputStream());
            while (true) {
                String type=(String)ois.readObject();
                System.out.println(type);
                if(type.equals("File")){
                    new FileTransport(s).run();
                }
                System.out.println("Object接受完毕!");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

工具类

package com.client;

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

/**
 * Created by ztc on 15-11-17.
 */
public class FileTransport {
    Socket s;
    public FileTransport(Socket s){
        this.s=s;
    }
    public void run(){
        try {
            System.out.println("Thread running>>>");
            DataInputStream dis = new DataInputStream(s.getInputStream());
            long length=dis.readLong();
            String name=dis.readUTF();
            DataOutputStream dos = new DataOutputStream(new FileOutputStream(new File(name)));
            int count=-1,sum=0;
            byte[] buffer=new byte[1024*1024];
            while((count=dis.read(buffer))!=-1){
                dos.write(buffer,0,count);
                sum+=count;
                System.out.println("已结收" + sum + "比特");
                if(sum==length)
                    break;
            }
            dos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}




posted @ 2015-11-17 18:26  A_yes  阅读(813)  评论(0编辑  收藏  举报