发送端:
import java.io.*;
import java.net.*;
public class Test {
public static void main(String[] args) throws IOException {
InetAddress address = InetAddress.getByName("OCTDN");
String ip = address.getHostAddress();
Socket sk = new Socket(ip,10000);
FileInputStream fis = new FileInputStream("Test.txt");
BufferedInputStream bis = new BufferedInputStream(fis);
OutputStream os = sk.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(os);
int b;
while ((b = bis.read()) != -1) {
bos.write(b);
}
sk.shutdownOutput();
InputStream is = sk.getInputStream();
BufferedReader bis1 = new BufferedReader(new InputStreamReader(is));
String a;
while ((a = bis1.readLine()) != null) {
System.out.println(a);
}
bis.close();
sk.close();
}
}
服务器:
import java.io.*;
import java.net.*;
public class Test01 {
public static void main(String[] args) throws IOException {
ServerSocket svk = new ServerSocket(10000);
Socket sk = svk.accept();
InputStream is = sk.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
FileOutputStream fos = new FileOutputStream("Test01.txt");
BufferedOutputStream bos = new BufferedOutputStream(fos);
int a;
byte b[] = new byte[1024];
while ((a = bis.read(b)) != -1) {
bos.write(b,0,b.length);
}
OutputStream ous = sk.getOutputStream();
BufferedWriter brw = new BufferedWriter(new OutputStreamWriter(ous));
String c = "上传成功";
brw.write(c);
brw.newLine();
brw.flush();
bos.close();
bis.close();
svk.close();
}
}
服务端有点点小的问题。
int a;
byte b[] = new byte[1024];
while ((a = bis.read(b)) != -1) {
// 这里改成了 a,而不是 b.length,因为 b 里面只有 b[0-a] 是有数据的,其他的是没有数据,或无效数据
bos.write(b,0, a);
}
客户端也要稍微改一下
while ((b = bis.read()) != -1) {
bos.write(b);
}
// 写完之后记得刷新一下
bos.flush();