使用TCP发送文件
客户端
package com.zy.demo3; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; public class TCPClient { public static void main(String[] args) throws Exception {//客户端 // 1创建socket对象 Socket socket = new Socket("localhost", 6666);//Socket(String host, int port) 创建流套接字并将其连接到指定主机上的指定端口号。 host写Ip和主机名都可以 //2得到输出流 OutputStream outputStream = socket.getOutputStream(); //3发送数据给服务端 //读取主机上的文件 //按文件流的方式,先读入内存,在写出去[边读编写] FileInputStream fileInputStream = new FileInputStream(new File("E:\\弹性表达式.doc"));//本地文件 byte b[]=new byte[1024]; int read = fileInputStream.read(b); while(read!=-1){ //-1表示读到末尾了 outputStream.write(b); read=fileInputStream.read(b); } //----------------------------- //接收响应 InputStream inputStream = socket.getInputStream(); byte re[]=new byte[1024]; inputStream.read(re); System.out.println("接收的响应是:"+new String(re).trim()); //4关闭资源 outputStream.close(); socket.close(); } }
服务端
package com.zy.demo3; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; public class TCPServer {//服务端 public static void main(String[] args) throws Exception { //基于流 //1创建serversocket对象 ServerSocket serverSocket = new ServerSocket(6666);//端口约定6666 //2获取socket对象(客户端) Socket accept = serverSocket.accept();//阻塞,即打开服务端后程序会运行到这一行,虚拟灯不灭,等待客户端发送数据 //3得到输入流 InputStream inputStream = accept.getInputStream(); //---------------- //响应(必须先响应再接收文件,否则客户端和服务端都在阻塞着,虚拟灯一直亮着) OutputStream outputStream = accept.getOutputStream(); outputStream.write("服务端已接收完毕,谢谢客户端".getBytes()); //--------------------- //4读取客户端发送数据 //将读取的数据存到本机文件 File file = new File("E:\\接收的文件\\1.doc");//接收的文件 File parentFile = file.getParentFile(); if (!parentFile.exists()) { parentFile.mkdirs(); } file.createNewFile(); FileOutputStream fileOutputStream = new FileOutputStream(file); byte b[]=new byte[1024]; int read = inputStream.read(b);//返回所占字节数(和FileInputStream一样,读取完毕时也返回-1) //边读编写 while(read!=-1){ fileOutputStream.write(b); read=inputStream.read(b); } System.out.println("接收完毕"); //5关闭资源 accept.close(); serverSocket.close(); } }
先运行服务端
再运行客户端
然后返回服务端