服务端:
package cn.net.tcp; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class uploadServer { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { System.out.println("服务端启动..."); ServerSocket ss = new ServerSocket(10005); Socket s = ss.accept(); String ip = s.getInetAddress().getHostAddress(); System.out.println(ip + "...connected"); BufferedReader bufr = new BufferedReader(new InputStreamReader( s.getInputStream())); PrintWriter pw = new PrintWriter(new FileWriter("server.txt"), true); String line = null; while ((line = bufr.readLine()) != null) { pw.println(line); } PrintWriter out = new PrintWriter(s.getOutputStream(), true); out.println("上传成功"); pw.close(); s.close(); ss.close(); } }
客户端:
package cn.net.tcp; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; public class uploadtxtClient { /** * @param args * @throws IOException * @throws UnknownHostException */ public static void main(String[] args) throws UnknownHostException, IOException { /* * 上传文本的客户端,读取本地文本数据,发送给服务端,服务端接收完毕后,回馈“上传成功”字样。 */ System.out.println("客户端启动了..."); Socket s = new Socket("127.0.0.1", 10005); BufferedReader bufr = new BufferedReader(new FileReader("client.txt")); PrintWriter out = new PrintWriter(s.getOutputStream(), true); String line = null; while ((line = bufr.readLine()) != null) { out.println(line); } s.shutdownOutput(); BufferedReader bufIn = new BufferedReader(new InputStreamReader( s.getInputStream())); String linIn = bufIn.readLine(); System.out.println(linIn); bufIn.close(); s.close(); } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-09-29 22:07:55