package netTest; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; // 发送数据的结束标记... 自定义结束标记,先告诉服务器自己的结束标记。 // 时间戳 socket 方法。。。 public class TextClient { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub Socket s = new Socket(InetAddress.getLocalHost(),7899); BufferedReader bufr = new BufferedReader(new FileReader("TcpClient.java")); PrintWriter out = new PrintWriter(s.getOutputStream(),true); long time = System.currentTimeMillis(); out.println(time); String line = null; while((line = bufr.readLine())!=null){ //System.out.println(line); out.println(line); } // 关闭客户端输出流 s.shutdownOutput(); //关闭输出流,相当于加了一个结束标记-1 // 自定义结束标记 out.println("over"); BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream())); String str = bufIn.readLine(); System.out.println(str); bufr.close(); s.close(); } } package netTest; 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 TextServer { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub ServerSocket ss = new ServerSocket(7899); Socket s = ss.accept(); System.out.println(s.getInetAddress().getLocalHost()+"...........connected"); BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream())); PrintWriter out = new PrintWriter(new FileWriter("server.java"),true); String line = null; while((line = bufIn.readLine())!=null){ //System.out.println(line); if("over".equals(line)){ // 自定义结束标记。 break; } out.println(line); } PrintWriter pw = new PrintWriter(s.getOutputStream(),true); pw.println("上传成功!!!"); out.close(); s.close(); ss.close(); } }
原文:http://www.cnblogs.com/yangyongqian/p/5143578.html