• 利用线程和管道的方式从客户端向服务的进行传送照片


    客户端:

    import java.io.*;
    //客户端
    public class PictureClient extends Thread{
    PipedOutputStream pos;
    public PictureClient() {
    // TODO Auto-generated constructor stub
    }
    public PictureClient(PipedOutputStream pos,String name) {
    this.pos = pos;
    setName(name);
    }
    private void WritePicture() {//添加读取该图片的方法
    //读取源文件
    String path = "src\作业2\WeChat.jpeg";
    try {
    FileInputStream fs = new FileInputStream(path);
    byte[] b = new byte[1024];
    int count = 0;
    while ((count = fs.read(b))!=-1) {//从is中读取b大小的内容存放到b中去。
    pos.write(b);
    pos.flush();
    }
    pos.close();
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    public void run() {
    //发送字符串,选择Data流
    WritePicture();
    }
    }

    服务器端:

    import java.io.*;

    public class PictureServer extends Thread {
    PipedInputStream pis;
    public PictureServer() {
    // TODO Auto-generated constructor stub
    }
    public PictureServer(PipedInputStream pis,String name) {
    super();
    this.pis = pis;
    setName(name);
    }
    private void ReaderPicture() {//添加写入到服务器端的方法
    String path2 = "src\作业2\We.jpeg";
    try {
    OutputStream os = new FileOutputStream(path2);
    byte[] b = new byte[1024];
    int count = 0;
    while ((count = pis.read(b))!=-1) {//从is中读取b大小的内容存放到b中去。
    os.write(b);
    os.flush();
    }
    os.close();
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    @Override
    public void run() {
    ReaderPicture();
    }
    }

    测试:

    import java.io.*;


    public class PictureThread {
    public static void main(String[] args) {
    PipedInputStream pis = new PipedInputStream();

    try {
    PipedOutputStream pos = new PipedOutputStream(pis);
    PictureClient pc = new PictureClient(pos,"发送方:");
    PictureServer ps = new PictureServer(pis,"接收方:");
    pc.start();
    ps.start();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    }

  • 相关阅读:
    awk,seq,xarg实例使用
    Docker安装yapi
    基于阿里搭载htppd访问
    锐捷结课作业
    基于centos7搭建kvm
    基于django实现简易版的图书管理系统
    python 自定义log模块
    Interesting Finds: 2008.01.13
    Interesting Finds: 2008.01.24
    Interesting Finds: 2008.01.17
  • 原文地址:https://www.cnblogs.com/xinchen01/p/10981766.html
Copyright © 2020-2023  润新知