网络编程 TCP学习
上传txt文本 通过socket向服务端发送数据 然后用serversocket 接收socket 通过流读取数据保存 服务端在发送确认信息并在client输出
client
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 txtClient { /** * @param args * @throws IOException * @throws UnknownHostException */ public static void main(String[] args) throws UnknownHostException, IOException { // TODO Auto-generated method stub Socket s = new Socket("10.64.130.51", 10002); BufferedReader br = new BufferedReader(new FileReader("F:\\fd.txt")); PrintWriter pw = new PrintWriter(s.getOutputStream(), true); String str = null; while((str = br.readLine()) != null){ //System.out.println(str); pw.println(str); } pw.println("over"); System.out.println("開始上传"); BufferedReader brin = new BufferedReader(new InputStreamReader(s.getInputStream())); str = brin.readLine(); System.out.println(str); br.close(); s.close(); } }
服务端
import java.io.*; import java.net.*; public class txtServer { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub ServerSocket ss = new ServerSocket(10002); Socket s = ss.accept(); BufferedReader brin= new BufferedReader(new InputStreamReader(s.getInputStream())); BufferedWriter bw = new BufferedWriter(new FileWriter("F:\\fd2.txt")); String str = null; System.out.println("接受中"); while((str = brin.readLine()) != null){ System.out.println(str); if(str.compareTo("over") == 0) break; bw.write(str); } //BufferedWriter bwout = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); PrintWriter pw = new PrintWriter(s.getOutputStream(), true); pw.println("上传成功"); bw.close(); s.close(); ss.close(); } }