客户端:
public static void main(String[] args) throws IOException {
Socket s = new Socket("127.0.0.1", 8899);
BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("F:\\IO\\test.png"));
BufferedInputStream bis2 = new BufferedInputStream(s.getInputStream());
int len;
byte[] bys = new byte[1024 * 4];
while ((len = bis.read(bys)) != -1) {
bos.write(bys, 0, len);
bos.flush();
}
s.shutdownOutput();
int len2;
byte[] bys2 = new byte[1024];
while ((len2 = bis2.read(bys2))!=-1){
System.out.println("返回:"+ new String(bys2,0,len2));
}
s.shutdownInput();
bis.close();
s.close();
}
服务端
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(8899);
while (true) {
Socket s = ss.accept();
BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
File file = new File("SQL-code\\copy.png");
while (file.exists()) {
file = new File("SQL-code\\copy" + System.currentTimeMillis() + ".png");
}
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
int len;
byte[] bys = new byte[1024 * 4];
while ((len = bis.read(bys)) != -1) {
bos.write(bys, 0, len);
bos.flush();
}
s.shutdownInput();
BufferedOutputStream serverBos = new BufferedOutputStream(s.getOutputStream());
serverBos.write("上传成功".getBytes(), 0, "上传成功".getBytes().length);
serverBos.flush();
s.shutdownOutput();
}
}