首页 > 编程语言 > 详细

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

时间:2019-06-05 22:35:25      阅读:92      评论:0      收藏:0      [点我收藏+]

客户端:

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();
}
}
}

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

原文:https://www.cnblogs.com/xinchen01/p/10981766.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!