【Java】TCP从客户端上传文件保存到服务端并给出反馈
作者:互联网
客户端
package LearnJava17.Tcptx3;
import java.io.*;
import java.net.Socket;
public class ClientDemo {
public static void main(String[] args) throws IOException {
Socket s=new Socket("127.0.0.1",10000);
BufferedReader br=new BufferedReader(new FileReader("D:\\MyProject\\Java\\Demo2\\src\\LearnJava17\\Tcptx3\\test.txt"));
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
String line;
while ((line=br.readLine())!=null){
bw.write(line);
bw.newLine();
bw.flush();
}
// 自定义结束标记
// bw.write("886");
// bw.newLine();
// bw.flush();
// 标准结束标记
s.shutdownOutput();
// 接收反馈
BufferedReader brClient=new BufferedReader(new InputStreamReader(s.getInputStream()));
String data = brClient.readLine();
System.out.println("服务器反馈:"+data);
s.close();
br.close();
}
}
服务端
package LearnJava17.Tcptx3;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerDemo {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(10000);
// 监听客户端连接
Socket s = ss.accept();
// 接收数据
BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedWriter bw=new BufferedWriter(new FileWriter("D:\\MyProject\\Java\\Demo2\\src\\LearnJava17\\Tcptx3\\test2.txt"));
String line;
while ((line=br.readLine())!=null){
// if ("886".equals(line)){
// break;
// }
bw.write(line);
bw.newLine();
bw.flush();
}
// 给出反馈
BufferedWriter bwServer =new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
bwServer.write("文件上传成功!");
bwServer.newLine();
bwServer.flush();
ss.close();
bw.close();
}
}
标签:Java,java,BufferedReader,TCP,BufferedWriter,bw,new,line,服务端 来源: https://www.cnblogs.com/HGNET/p/16210610.html