服务器:
public class FileServerDemo {
public static void main(String[] args) throws IOException {
//创建服务器对象
ServerSocket ss = new ServerSocket(8080);
//监听
Socket s = ss.accept();
//包装通道内的输入流
BufferedInputStream bis = new BufferedInputStream(
s.getInputStream());
//把数据写入文件
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream("C:\\Users\\MA\\Desktop\\IOtest\\copy.jpg"));
byte[] bys = new byte[1024];
int len = 0;
while((len = bis.read(bys))!=-1){
bos.write(bys,0,len);
}
//把通道内的输出流包装
BufferedWriter write = new BufferedWriter(new OutputStreamWriter(
s.getOutputStream()));
write.write("文件上传成功");
write.newLine();
write.flush();
//释放资源
bos.close();
s.close();
ss.close();
}
}
客户端:
public class FileClientDemo {
public static void main(String[] args) throws IOException {
//创建客户端对象
Socket s = new Socket("172.24.60.182",8080);
//读取文件的数据
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("C:\\Users\\MA\\Desktop\\电路指导书\\QQ图片20180627212519.jpg"));
//把通道内的输出流包装
BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
byte[] bys = new byte[1024];
int len = 0;
while((len=bis.read(bys))!=-1){
bos.write(bys,0,len);
}
//给服务器一个反馈
s.shutdownOutput();//禁用输出流
//获取服务器的反馈信息
BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
String data = reader.readLine();
System.out.println("client:"+data);
bis.close();
s.close();
}
}
原文地址:https://www.cnblogs.com/mxj961116/p/9348732.html