利用TCP协议下一个简版的文件传输
发送文件客户端
1 package Package1; 2 3 import java.io.BufferedInputStream; 4 import java.io.BufferedOutputStream; 5 import java.io.File; 6 import java.io.FileInputStream; 7 import java.io.IOException; 8 import java.net.InetAddress; 9 import java.net.Socket;10 import java.net.UnknownHostException;11 12 public class 发送文件客户端 {13 14 public static void main(String[] args) throws IOException, IOException {15 try(16 Socket s=new Socket(InetAddress.getByName("localhost"),9002);17 BufferedInputStream bis=new BufferedInputStream(new FileInputStream(new File("C:\\Users\\Administrator\\Desktop\\4.19.txt")));18 BufferedOutputStream bos=new BufferedOutputStream(s.getOutputStream());19 20 ){21 byte[] bt=new byte[1024];22 int count=0;23 while((count=bis.read(bt))!=-1) {24 bos.write(bt,0,count);25 }26 bos.flush();27 }catch(Exception e) {28 e.printStackTrace();29 }30 31 }32 33 }
服务器端:
1 package Package1; 2 3 import java.io.BufferedInputStream; 4 import java.io.BufferedOutputStream; 5 import java.io.File; 6 import java.io.FileOutputStream; 7 import java.io.IOException; 8 import java.net.ServerSocket; 9 import java.net.Socket;10 11 public class 发送文件服务器端 {12 13 public static void main(String[] args) throws Exception {14 try(15 ServerSocket ss=new ServerSocket(9002);16 17 ){18 try(19 Socket s=ss.accept();20 BufferedInputStream bis=new BufferedInputStream(s.getInputStream()); 21 BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(new File("upload\\2.txt")));22 23 ){24 byte[] bt=new byte[1024];25 int count=0;26 while((count=bis.read())!=-1) {27 bos.write(bt,0,count);28 }29 }30 }31 32 }33 34 }