标签:soc tst system load prope etc void exce 服务器
1、Client
package cn.qi.Client; import java.io.*; import java.net.Socket; public class Client { Socket clientSocket; Client() { // 建立连接到服务器端的socket try { clientSocket = new Socket("127.0.0.1", 5000); } catch (IOException e) { e.printStackTrace(); } } public void readFileAndSent() throws IOException { OutputStream os = clientSocket.getOutputStream(); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os)); // 读文件 String path = this.getClass().getClassLoader().getResource("./prop/text.txt").getPath(); FileReader fr = new FileReader(path); BufferedReader br = new BufferedReader(fr); String str = null; while((str = br.readLine()) != null) { System.out.println(str); // 每读一行,写一行 bw.write(str); // 获取当前OS的换行符并写入 bw.write(System.getProperty("line.separator")); bw.flush(); } // 关闭流 bw.close(); br.close(); fr.close(); clientSocket.close(); } }
2、Server
package cn.qi.Server; import java.io.*; import java.net.ServerSocket; import java.net.Socket; public class Server { ServerSocket serverSocket; Server() { // 建立severSocket,监听对应端口 try { serverSocket = new ServerSocket(5000); } catch (IOException e) { e.printStackTrace(); } } public void readFileAndWrite() throws IOException { // 获取写入路径 String path = this.getClass().getClassLoader().getResource("./prop/").getPath(); // 服务器端写文件 FileWriter fw = new FileWriter(path+"textSocket.txt"); BufferedWriter bw = new BufferedWriter(fw); // 写的内容来自网络端 while (true) { Socket socket = serverSocket.accept(); InputStream is = socket.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String str = null; while((str = br.readLine()) != null) { // 读到了客户端发送的信息 bw.write(str); // 获取当前OS的换行符并写入 bw.write(System.getProperty("line.separator")); bw.flush(); } // 关闭流 br.close(); socket.close(); } } }
标签:soc tst system load prope etc void exce 服务器
原文地址:https://www.cnblogs.com/GjqDream/p/11624327.html