带有反馈版本:
客户端:
- package com.kxg_10;
- import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.net.Socket;
- public class ClientDemo {
- public static void main(String[] args) throws IOException {
- Socket s = new Socket("10.164.22.254", 48264);
- BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
- "a.txt"));
- 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);
- // 需要刷新,不然数据写不进去
- bos.flush();
- }
- // 通知服务器已经完成了传输
- s.shutdownOutput();
- InputStream bis2 = s.getInputStream();
- byte[] bys2 = new byte[1024];
- int len2 = bis2.read(bys2);
- String str = new String(bys2, 0, len2);
- System.out.println(str);
- bis.close();
- s.close();
- }
- }
复制代码 服务器端:
- package com.kxg_10;
- import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.OutputStream;
- import java.net.ServerSocket;
- import java.net.Socket;
- public class ServerDemo {
- public static void main(String[] args) throws IOException {
- ServerSocket ss = new ServerSocket(48264);
- Socket s = ss.accept();
- BufferedOutputStream bos = new BufferedOutputStream(
- new FileOutputStream("Copy.txt"));
- BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
- byte[] bys = new byte[1024];
- int len = 0;
- while ((len = bis.read(bys)) != -1) {
- bos.write(bys, 0, len);
- }
- OutputStream bos2 = s.getOutputStream();
- bos2.write("上传成功".getBytes());
- s.close();
- bos.close();
- }
- }
复制代码
|