实现步骤
-
-
创建服务器对象,创建输出流对象指向文件,每接受一行数据就使用输出流输出到文件中,传输结束后。使用输出流给客户端反馈信息
-
服务端
package TCPDemo;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerDemo {
public static void main(String[] args) throws IOException {
//创建服务器端Socket(ServerSocket)
ServerSocket ss = new ServerSocket(10086);
//监听客户端连接,返回一个对应的Socket对象
Socket sc = ss.accept();
//创建字符缓冲输入流,接受数据
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(sc.getInputStream()));
//创建字符缓冲输出对象,将数据写入文件中
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("UDPandTCPdemo\\gg.txt"));
//创建字符串对象,用来存放数据
String line;
//循环读取数据
while ((line = bufferedReader.readLine()) != null) {
//写入
bufferedWriter.write(line);
//写一行行分隔符
bufferedWriter.newLine();
//刷新流
bufferedWriter.flush();
}
//服务器提供反馈
BufferedWriter bufferedWriter1 = new BufferedWriter(new OutputStreamWriter(sc.getOutputStream()));
bufferedWriter1.write("文件上传成功");
bufferedWriter1.newLine();
bufferedWriter1.flush();
bufferedWriter.close();
//释放资源
ss.close();
}
}
客户端
package TCPDemo;
import java.io.*;
import java.net.Socket;
public class ClientDemo {
public static void main(String[] args) throws IOException {
//创建客端Socket对象
Socket sc =new Socket("192.168.1.210",10086);
//封装数据包,创建缓冲字符输入流对象,用来封装文本文件
BufferedReader bufferedReader = new BufferedReader(new FileReader("UDPandTCPdemo\\ReceiveDemo.java"));
//创建字符缓冲输出流,将数据封装到流中并写入数据
BufferedWriter bf =new BufferedWriter(new OutputStreamWriter(sc.getOutputStream()));
//创建字符串对象,写入数据
String line;
//while循环,读取字符缓冲输入流对象
while ((line = bufferedReader.readLine())!=null){
//写入到字符缓冲输出流对象中
bf.write(line);
bf.newLine();
bf.flush();
}
//禁用此套接字的输出流
sc.shutdownOutput();
//接受反馈
BufferedReader bufferedReader1 = new BufferedReader(new InputStreamReader(sc.getInputStream()));
//等待读取数据
String data = bufferedReader1.readLine();
//返回结果
System.out.println("服务器反馈 "+data);
//释放资源
bufferedReader1.close();
sc.close();
}
}