展开菜单
首页 精品内容 本月促销 装机必备 Windows PDF教程 macOS软件 IOS软件 Android AI 专题
全部分类

当前位置:

首页 > 系统应用 > 7.6.3 基于TCP协议的Socket通信(2)

7.6.3 基于TCP协议的Socket通信(2)

本节引言: 上一节已经带大家过了一遍 Socket 的基础概念和常见用法,还顺手做了一个“小猪简易聊天室”的 Demo。看到这里,大家对 Socket 应该已经有了一个基本认识。接下来,内容再往前走一步:用 Socket 来实现大文件的断点续传。这里要说明一下,本节讲解的是一个别人已经写好的 Soc

本文目录

    本节引言:

    上一节已经带大家过了一遍 Socket 的基础概念和常见用法,还顺手做了一个“小猪简易聊天室”的 Demo。看到这里,大家对 Socket 应该已经有了一个基本认识。接下来,内容再往前走一步:用 Socket 来实现大文件的断点续传。这里要说明一下,本节讲解的是一个别人已经写好的 Socket 大文件上传示例,重点不在于从零独立写出来,而是先把思路和用法吃透,等真正要用的时候,能直接上手,这就够了。

    1.运行效果图:

    1.先把我们编写好的Socket服务端运行起来:

    2.将一个音频文件放到SD卡根目录下:

    3.运行我们的客户端:

    4.上传成功后可以看到我们的服务端的项目下生成一个file的文件夹,我们可以在这里找到上传的文件: .log那个是我们的日志文件

    2.实现流程图:

    3.代码示例:

    先编写一个服务端和客户端都会用到的流解析类:

    StreamTool.ja va:

    public class StreamTool {
        public static void sa ve(File file, byte[] data) throws Exception {
            FileOutputStream outStream = new FileOutputStream(file);
            outStream.write(data);
            outStream.close();
        }
        public static String readLine(PushbackInputStream in) throws IOException {
            char buf[] = new char[128];
            int room = buf.length;
            int offset = 0;
            int c;
            loop:       while (true) {
                switch (c = in.read()) {
                    case -1:
                    case 'n':
                        break loop;
                    case 'r':
                        int c2 = in.read();
                        if ((c2 != 'n') && (c2 != -1)) in.unread(c2);
                        break loop;
                    default:
                        if (--room < 0) {
                            char[] lineBuffer = buf;
                            buf = new char[offset + 128];
                            room = buf.length - offset - 1;
                            System.arraycopy(lineBuffer, 0, buf, 0, offset);
                        }
                        buf[offset++] = (char) c;
                        break;
                }
            }
            if ((c == -1) && (offset == 0)) return null;
            return String.copyValueOf(buf, 0, offset);
        }
        /**
         * 读取流
         * @param inStream
         * @return 字节数组
         * @throws Exception
         */
        public static byte[] readStream(InputStream inStream) throws Exception{
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = -1;
            while( (len=inStream.read(buffer)) != -1){
                outSteam.write(buffer, 0, len);
            }
            outSteam.close();
            inStream.close();
            return outSteam.toByteArray();
        }
    } 

    1)服务端的实现:

    socket管理与多线程管理类:

    FileServer.ja va:

    public class FileServer {  
    private ExecutorService executorService;//线程池  
        private int port;//监听端口  
        private boolean quit = false;//退出  
        private ServerSocket server;  
        private Map datas = new HashMap();//存放断点数据  
    public FileServer(int port){  
            this.port = port;  
            //创建线程池,池中具有(cpu个数*50)条线程  
            executorService = Executors.newFixedThreadPool(Runtime.getRuntime().a vailableProcessors() * 50);  
        }  
        /** 
         * 退出 
         */  
        public void quit(){  
           this.quit = true;  
           try {  
               server.close();  
           } catch (IOException e) {  
           }  
        }  
        /** 
         * 启动服务 
         * @throws Exception 
         */  
        public void start() throws Exception{  
            server = new ServerSocket(port);  
            while(!quit){  
                try {  
                  Socket socket = server.accept();  
                  //为支持多用户并发访问,采用线程池管理每一个用户的连接请求  
                  executorService.execute(new SocketTask(socket));  
                } catch (Exception e) {  
                  //  e.printStackTrace();  
                }  
            }  
        }  
    private final class SocketTask implements Runnable{  
           private Socket socket = null;  
           public SocketTask(Socket socket) {  
               this.socket = socket;  
           }  
    public void run() {  
               try {  
                   System.out.println("accepted connection "+ socket.getInetAddress()+ ":"+ socket.getPort());  
                   PushbackInputStream inStream = new PushbackInputStream(socket.getInputStream());  
                   //得到客户端发来的第一行协议数据:Content-Length=143253434;filename=xxx.3gp;sourceid=  
                   //如果用户初次上传文件,sourceid的值为空。  
                   String head = StreamTool.readLine(inStream);  
                   System.out.println(head);  
                   if(head!=null){  
                       //下面从协议数据中提取各项参数值  
                       String[] items = head.split(";");  
                       String filelength = items[0].substring(items[0].indexOf("=")+1);  
                       String filename = items[1].substring(items[1].indexOf("=")+1);  
                       String sourceid = items[2].substring(items[2].indexOf("=")+1);        
                       long id = System.currentTimeMillis();//生产资源id,如果需要唯一性,可以采用UUID  
                       FileLog log = null;  
                       if(sourceid!=null && !"".equals(sourceid)){  
                           id = Long.valueOf(sourceid);  
                           log = find(id);//查找上传的文件是否存在上传记录  
                       }  
                       File file = null;  
                       int position = 0;  
                       if(log==null){//如果不存在上传记录,为文件添加跟踪记录  
                           String path = new SimpleDateFormat("yyyy/MM/dd/HH/mm").format(new Date());  
                           File dir = new File("file/"+ path);  
                           if(!dir.exists()) dir.mkdirs();  
                           file = new File(dir, filename);  
                           if(file.exists()){//如果上传的文件发生重名,然后进行改名  
                               filename = filename.substring(0, filename.indexOf(".")-1)+ dir.listFiles().length+ filename.substring(filename.indexOf("."));  
                               file = new File(dir, filename);  
                           }  
                           sa ve(id, file);  
                       }else{// 如果存在上传记录,读取已经上传的数据长度  
                           file = new File(log.getPath());//从上传记录中得到文件的路径  
                           if(file.exists()){  
                               File logFile = new File(file.getParentFile(), file.getName()+".log");  
                               if(logFile.exists()){  
                                   Properties properties = new Properties();  
                                   properties.load(new FileInputStream(logFile));  
                                   position = Integer.valueOf(properties.getProperty("length"));//读取已经上传的数据长度  
                               }  
                           }  
                       }  
    OutputStream outStream = socket.getOutputStream();  
                       String response = "sourceid="+ id+ ";position="+ position+ "rn";  
                       //服务器收到客户端的请求信息后,给客户端返回响应信息:sourceid=1274773833264;position=0  
                       //sourceid由服务器端生成,唯一标识上传的文件,position指示客户端从文件的什么位置开始上传  
                       outStream.write(response.getBytes());  
    RandomAccessFile fileOutStream = new RandomAccessFile(file, "rwd");  
                       if(position==0) fileOutStream.setLength(Integer.valueOf(filelength));//设置文件长度  
                       fileOutStream.seek(position);//指定从文件的特定位置开始写入数据  
                       byte[] buffer = new byte[1024];  
                       int len = -1;  
                       int length = position;  
                       while( (len=inStream.read(buffer)) != -1){//从输入流中读取数据写入到文件中  
                           fileOutStream.write(buffer, 0, len);  
                           length += len;  
                           Properties properties = new Properties();  
                           properties.put("length", String.valueOf(length));  
                           FileOutputStream logFile = new FileOutputStream(new File(file.getParentFile(), file.getName()+".log"));  
                           properties.store(logFile, null);//实时记录已经接收的文件长度  
                           logFile.close();  
                       }  
                       if(length==fileOutStream.length()) delete(id);  
                       fileOutStream.close();                    
                       inStream.close();  
                       outStream.close();  
                       file = null;  
    }  
               } catch (Exception e) {  
                   e.printStackTrace();  
               }finally{  
                   try {  
                       if(socket!=null && !socket.isClosed()) socket.close();  
                   } catch (IOException e) {}  
               }  
           }  
        }  
    public FileLog find(Long sourceid){  
            return datas.get(sourceid);  
        }  
        //保存上传记录  
        public void sa ve(Long id, File sa veFile){  
            //日后可以改成通过数据库存放  
            datas.put(id, new FileLog(id, sa veFile.getAbsolutePath()));  
        }  
        //当文件上传完毕,删除记录  
        public void delete(long sourceid){  
            if(datas.containsKey(sourceid)) datas.remove(sourceid);  
        }  
    private class FileLog{  
           private Long id;  
           private String path;  
           public Long getId() {  
               return id;  
           }  
           public void setId(Long id) {  
               this.id = id;  
           }  
           public String getPath() {  
               return path;  
           }  
           public void setPath(String path) {  
               this.path = path;  
           }  
           public FileLog(Long id, String path) {  
               this.id = id;  
               this.path = path;  
           }     
        }  
    }  

    服务端界面类:ServerWindow.ja va:

    public class ServerWindow extends Frame {
        private FileServer s = new FileServer(12345);
        private Label label;
        public ServerWindow(String title) {
            super(title);
            label = new Label();
            add(label, BorderLayout.PAGE_START);
            label.setText("服务器已经启动");
            this.addWindowListener(new WindowListener() {
                public void windowOpened(WindowEvent e) {
                    new Thread(new Runnable() {
                        public void run() {
                            try {
                                s.start();
                            } catch (Exception e) {
                                // e.printStackTrace();
                            }
                        }
                    }).start();
                }
                public void windowIconified(WindowEvent e) {
                }
                public void windowDeiconified(WindowEvent e) {
                }
                public void windowDeactivated(WindowEvent e) {
                }
                public void windowClosing(WindowEvent e) {
                    s.quit();
                    System.exit(0);
                }
                public void windowClosed(WindowEvent e) {
                }
                public void windowActivated(WindowEvent e) {
                }
            });
        }
        /**
         * @param args
         */
        public static void main(String[] args) throws IOException {
            InetAddress address = InetAddress.getLocalHost();
            ServerWindow window = new ServerWindow("文件上传服务端:" + address.getHostAddress());
            window.setSize(400, 300);
            window.setVisible(true);
        }
    }

    2)客户端(Android端)

    首先是布局文件:activity_main.xml:

    
    
    
    
    

    因为断点续传,我们需要保存上传的进度,我们需要用到数据库,这里我们定义一个数据库 管理类:DBOpenHelper.ja va::

    /**
     * Created by Jay on 2015/9/17 0017.
     */
    public class DBOpenHelper extends SQLiteOpenHelper {
    public DBOpenHelper(Context context) {
            super(context, "jay.db", null, 1);
        }
    @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("CREATE TABLE IF NOT EXISTS uploadlog (_id integer primary key autoincrement, path varchar(20), sourceid varchar(20))");
        }
    @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }
    }

    然后是数据库操作类:UploadHelper.ja va:

    /**
     * Created by Jay on 2015/9/17 0017.
     */
    public class UploadHelper {
        private DBOpenHelper dbOpenHelper;
    public UploadHelper(Context context) {
            dbOpenHelper = new DBOpenHelper(context);
        }
    public String getBindId(File file) {
            SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
            Cursor cursor = db.rawQuery("select sourceid from uploadlog where path=?", new String[]{file.getAbsolutePath()});
            if (cursor.moveToFirst()) {
                return cursor.getString(0);
            }
            return null;
        }
    public void sa ve(String sourceid, File file) {
            SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
            db.execSQL("insert into uploadlog(path,sourceid) values(?,?)",
                    new Object[]{file.getAbsolutePath(), sourceid});
        }
    public void delete(File file) {
            SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
            db.execSQL("delete from uploadlog where path=?", new Object[]{file.getAbsolutePath()});
        }
    }

    对了,别忘了客户端也要贴上那个流解析类哦,最后就是我们的MainActivity.ja va了:

    public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText edit_fname;
        private Button btn_upload;
        private Button btn_stop;
        private ProgressBar pgbar;
        private TextView txt_result;
    private UploadHelper upHelper;
        private boolean flag = true;
    private Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                pgbar.setProgress(msg.getData().getInt("length"));
                float num = (float) pgbar.getProgress() / (float) pgbar.getMax();
                int result = (int) (num * 100);
                txt_result.setText(result + "%");
                if (pgbar.getProgress() == pgbar.getMax()) {
                    Toast.makeText(MainActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
                }
            }
        };
    @Override
        public void onCreate(Bundle sa vedInstanceState) {
            super.onCreate(sa vedInstanceState);
            setContentView(R.layout.activity_main);
            bindViews();
            upHelper = new UploadHelper(this);
        }
    private void bindViews() {
            edit_fname = (EditText) findViewById(R.id.edit_fname);
            btn_upload = (Button) findViewById(R.id.btn_upload);
            btn_stop = (Button) findViewById(R.id.btn_stop);
            pgbar = (ProgressBar) findViewById(R.id.pgbar);
            txt_result = (TextView) findViewById(R.id.txt_result);
    btn_upload.setOnClickListener(this);
            btn_stop.setOnClickListener(this);
        }
    @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_upload:
                    String filename = edit_fname.getText().toString();
                    flag = true;
                    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                        File file = new File(Environment.getExternalStorageDirectory(), filename);
                        if (file.exists()) {
                            pgbar.setMax((int) file.length());
                            uploadFile(file);
                        } else {
                            Toast.makeText(MainActivity.this, "文件并不存在~", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(MainActivity.this, "SD卡不存在或者不可用", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case R.id.btn_stop:
                    flag = false;
                    break;
            }
        }
    private void uploadFile(final File file) {
            new Thread(new Runnable() {
                public void run() {
                    try {
                        String sourceid = upHelper.getBindId(file);
                        Socket socket = new Socket("172.16.2.54", 12345);
                        OutputStream outStream = socket.getOutputStream();
                        String head = "Content-Length=" + file.length() + ";filename=" + file.getName()
                                + ";sourceid=" + (sourceid != null ? sourceid : "") + "rn";
                        outStream.write(head.getBytes());
    PushbackInputStream inStream = new PushbackInputStream(socket.getInputStream());
                        String response = StreamTool.readLine(inStream);
                        String[] items = response.split(";");
                        String responseSourceid = items[0].substring(items[0].indexOf("=") + 1);
                        String position = items[1].substring(items[1].indexOf("=") + 1);
                        if (sourceid == null) {//如果是第一次上传文件,在数据库中不存在该文件所绑定的资源id
                            upHelper.sa ve(responseSourceid, file);
                        }
                        RandomAccessFile fileOutStream = new RandomAccessFile(file, "r");
                        fileOutStream.seek(Integer.valueOf(position));
                        byte[] buffer = new byte[1024];
                        int len = -1;
                        int length = Integer.valueOf(position);
                        while (flag && (len = fileOutStream.read(buffer)) != -1) {
                            outStream.write(buffer, 0, len);
                            length += len;//累加已经上传的数据长度
                            Message msg = new Message();
                            msg.getData().putInt("length", length);
                            handler.sendMessage(msg);
                        }
                        if (length == file.length()) upHelper.delete(file);
                        fileOutStream.close();
                        outStream.close();
                        inStream.close();
                        socket.close();
                    } catch (Exception e) {
                        Toast.makeText(MainActivity.this, "上传异常~", Toast.LENGTH_SHORT).show();
                    }
                }
            }).start();
        }
    }

    最后,还有,记得往**AndroidManifest.xml**中写入这些权限哦!

    
    
    
    
    
    

    4.代码下载:

    Socket上传大文件demo

    5.本节小结:

    本节给大家介绍了基于TCP协议的Socket的另一个实例:使用Socket完成大文件的续传, 相信大家对Socket的了解更进一步,嗯,下一节再写一个例子吧,两个处于同一Wifi 下的手机相互传递数据的实例吧!就说这么多,谢谢~

    本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系bd@zhengruan.com
    作者最新文章
    系统应用
    相关文章 更多
    精品专题 更多
    装机必备

    正软商城装机必备专区,精选办公、浏览器、安全防护、影音播放、压缩解压、设计创作和系统工具等电脑常用正版软件,帮助用户快速完成新电脑软件配置。

    Windows

    正软商城Windows软件专区,汇集适用于Windows电脑的办公、设计、安全防护、影音播放、开发工具和系统优化软件,提供软件介绍、系统要求、正版授权及购买下载服务。

    PDF教程

    正软商城PDF教程频道提供PDF编辑、转换、合并、拆分、压缩及格式处理方法,同时介绍常用PDF软件和工具的使用技巧。

    macOS软件

    正软商城macOS软件专区,精选适用于Mac电脑的办公、设计、影音、效率、开发和系统工具,提供软件功能介绍、macOS兼容版本、正版授权及购买下载服务。

    IOS软件

    正软商城iOS软件专区,精选适用于iPhone和iPad的办公、学习、影音、设计、效率及AI应用,提供功能介绍、适用设备、系统要求和正版获取方式等信息。

    AI

    正软商城AI软件专区,汇集AI写作、AI绘画、AI视频、AI办公、AI编程、AI翻译、智能客服和数据分析等人工智能工具,提供功能介绍、适用平台、收费方式及正版购买信息。

    Mac软件 更多
    Aperty macOS版
    Aperty macOS版

    Aperty 是 Skylum 推出的 AI 人像修图软件,支持自然肤质修饰、瑕疵处理、面部与身体调整、预设及批量同步。

    火山引擎 网页版
    火山引擎 网页版

    火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

    立刻MV 网页版
    立刻MV 网页版

    立刻MV 面向音乐人、内容创作者和品牌团队,帮助用户低成本完成歌曲 MV、歌词视频、AI 分镜、图生视频与最终合成。

    蛙蛙写作 网页版
    蛙蛙写作 网页版

    蛙蛙写作 AI 创作工具,覆盖小说、剧本、文案,一键生成文稿,打通文字转视频全流程,高效解决创作难题。

    讯飞智作 网页版
    讯飞智作 网页版

    讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

    超级简历WonderCV 网页版
    超级简历WonderCV 网页版

    超级简历WonderCV是面向应届生和AI小白的智能求职平台,覆盖简历、面试与职业规划。

    音述AI 网页版
    音述AI 网页版

    音述AI,是一个以“用声音述说故事”为核心的 AI 音乐创作与声音分享社区。

    AionClaw macOS版
    AionClaw macOS版

    AionClaw 是可在桌面端运行的任务型 AI 助手,通过数字专家与技能市场组合办公、创作、数据和开发能力。

    Loomy macOS版
    Loomy macOS版

    Loomy 是科大讯飞推出的桌面 AI 助手,可通过对话、任务与工作目录协助处理办公、内容创作和资料整理。

    AirBuddy 3 macOS版
    AirBuddy 3 macOS版

    AirBuddy 3 是面向 macOS 的蓝牙外设增强工具,可集中查看 AirPods、Beats 与苹果设备电量,提供快速连接、播放控制、电量提醒、桌面小组件和多台 Mac 外设接力等功能。

    AirServer macOS版
    AirServer macOS版

    AirServer macOS版可把 Mac 转换为无线投屏接收端,通过 AirPlay 或 Google Cast 接收手机、平板和电脑画面,并支持多设备同时连接、高清镜像及会话录制,适合家庭娱乐、课堂教学、会议演示和应用展示。

    AnyDesk macOS版
    AnyDesk macOS版

    AnyDesk macOS版是一款适用于远程办公、设备维护和客户支持的远程桌面工具,可连接并操作异地计算机,支持文件传输、无人值守访问、会话权限控制及跨平台协作。

    WINDOWS 更多
    讯飞绘文 网页版
    讯飞绘文 网页版

    讯飞绘文网页版是科大讯飞推出的AI图文创作与内容运营工具,覆盖热点选题、文章生成、稿件校对、智能配图、排版发布和数据复盘等环节,适合自媒体创作者及内容团队在线使用。

    Maya(Autodesk Maya) Windows版
    Maya(Autodesk Maya) Windows版

    Autodesk Maya 是面向影视、电视、动画和游戏行业的专业三维制作软件,集多边形与 NURBS 建模、角色绑定、关键帧和动作捕捉动画、Bifrost 特效模拟、材质开发及 Arnold 渲染于一体,

    Aperty Windows版
    Aperty Windows版

    Aperty 是 Skylum 推出的 AI 人像修图软件,支持自然肤质修饰、瑕疵处理、面部与身体调整、预设及批量同步。

    火山引擎 网页版
    火山引擎 网页版

    火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

    立刻MV 网页版
    立刻MV 网页版

    立刻MV 面向音乐人、内容创作者和品牌团队,帮助用户低成本完成歌曲 MV、歌词视频、AI 分镜、图生视频与最终合成。

    蛙蛙写作 网页版
    蛙蛙写作 网页版

    蛙蛙写作 AI 创作工具,覆盖小说、剧本、文案,一键生成文稿,打通文字转视频全流程,高效解决创作难题。

    讯飞智作 网页版
    讯飞智作 网页版

    讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

    超级简历WonderCV 网页版
    超级简历WonderCV 网页版

    超级简历WonderCV是面向应届生和AI小白的智能求职平台,覆盖简历、面试与职业规划。

    音述AI 网页版
    音述AI 网页版

    音述AI,是一个以“用声音述说故事”为核心的 AI 音乐创作与声音分享社区。

    AionClaw Windows版
    AionClaw Windows版

    AionClaw 是可在桌面端运行的任务型 AI 助手,通过数字专家与技能市场组合办公、创作、数据和开发能力。

    Loomy Windows版
    Loomy Windows版

    Loomy 是科大讯飞推出的桌面 AI 助手,可通过对话、任务与工作目录协助处理办公、内容创作和资料整理。

    AirServer Windows版
    AirServer Windows版

    AirServer Windows版可把电脑变成AirPlay、Google Cast和Miracast无线投屏接收端,适合会议演示、课堂教学及家庭大屏分享。发送设备通常无需另装客户端,并可同时接收和智能排列多个镜像会话。