1. TCP协议上传文本文件(客户端上传数据到服务器端)
(1)客户端(上传数据到服务端)
1 package cn.itcast_11; 2 3 import java.io.BufferedReader; 4 import java.io.BufferedWriter; 5 import java.io.FileReader; 6 import java.io.IOException; 7 import java.io.OutputStreamWriter; 8 import java.net.Socket; 9 10 public class UploadClient { 11 public static void main(String[] args) throws IOException { 12 // 创建客户端Socket对象 13 Socket s = new Socket("192.168.12.92", 11111); 14 15 // 封装文本文件 16 BufferedReader br = new BufferedReader(new FileReader( 17 "InetAddressDemo.java")); 18 // 封装通道内流 19 BufferedWriter bw = new BufferedWriter(new OutputStreamWriter( 20 s.getOutputStream())); 21 22 String line = null; 23 while ((line = br.readLine()) != null) { 24 bw.write(line); 25 bw.newLine(); 26 bw.flush(); 27 } 28 29 // 释放资源 30 br.close(); 31 s.close(); 32 } 33 }
(2)服务端(接收来自客户端的数据)
1 package cn.itcast_11; 2 3 import java.io.BufferedReader; 4 import java.io.BufferedWriter; 5 import java.io.FileWriter; 6 import java.io.IOException; 7 import java.io.InputStreamReader; 8 import java.net.ServerSocket; 9 import java.net.Socket; 10 11 public class UploadServer { 12 public static void main(String[] args) throws IOException { 13 // 创建服务器端的Socket对象 14 ServerSocket ss = new ServerSocket(11111); 15 16 // 监听客户端连接 17 Socket s = ss.accept(); 18 19 // 封装通道内的流 20 BufferedReader br = new BufferedReader(new InputStreamReader( 21 s.getInputStream())); 22 // 封装文本文件 23 BufferedWriter bw = new BufferedWriter(new FileWriter("Copy.java")); 24 25 String line = null; 26 while ((line = br.readLine()) != null) { 27 bw.write(line); 28 bw.newLine(); 29 bw.flush(); 30 } 31 32 bw.close(); 33 s.close(); 34 } 35 }