public class FileClient {
public static final String SRC_FILE="data.txt";
public static void main(String[] args) throws Exception {
start();
}
public static void start() throws Exception {
Socket s = new Socket("127.0.0.1", 9999);
File file = new File(SRC_FILE);
BufferedReader bfr = new BufferedReader(new FileReader(file));
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
int posi = file.getName().lastIndexOf(".");
String suffix = file.getName().substring(posi);
System.out.println(suffix);
out.println(suffix);
String line = null;
while ((line = bfr.readLine()) != null) {
out.println(line);
}
s.shutdownOutput();//关闭客户端的输出流,相当于给流中加入一个结束标记
BufferedReader bufIn = new BufferedReader(new InputStreamReader(
s.getInputStream()));
System.out.println(bufIn.readLine());
bfr.close();
bufIn.close();
s.close();
}
}
服务器端代码:
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class FileServer {
public static void main(String[] args) throws Exception {
start();
}
public static void start() throws Exception {
ServerSocket server = new ServerSocket(9999);
System.out.println("服务已经启动.......");
Socket s = server.accept();
String ip = s.getInetAddress().getHostAddress();
System.out.println(ip + ".......connected");