客户端
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws IOException {
//创建对象
Socket socket = new Socket(InetAddress.getLocalHost(), 12345);
//读取文件
BufferedReader bufferedReader = new BufferedReader(new FileReader("E:\\Workpace\\ReviceSocket1.java"));
//封装输出流
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
String line;
while ((line = bufferedReader.readLine()) != null){
bufferedWriter.write(line);
bufferedWriter.newLine();
bufferedWriter.flush();
}
socket.shutdownOutput();
bufferedReader.close();
//接受服务器反馈
BufferedReader bufferedReader1 = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println(bufferedReader1.readLine());
socket.close();
}
}
服务端
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
//创建对象
ServerSocket serverSocket = new ServerSocket(12345);
Socket accept = serverSocket.accept();
int count = 0;
String filename = "Example1\\ReviceSocket"+count+".java";
File file = new File(filename);
if (!file.exists()){
count++;
filename = "Example1\\ReviceSocket"+count+".java";
}
//下载文件
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filename));
//封装输入流
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(accept.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null){
bufferedWriter.write(line);
bufferedWriter.newLine();
bufferedWriter.flush();
}
//输出反馈信息
BufferedWriter bufferedWriter1 = new BufferedWriter(new OutputStreamWriter(accept.getOutputStream()));
bufferedWriter1.write("文件已上传");
bufferedWriter1.newLine();
bufferedWriter1.flush();
bufferedWriter.close();
serverSocket.close();
}
}