客户端+服务端2(提升)
需先执行服务端,再执行客户端package reflect;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import .ServerSocket;import .Socket;//服务端public class TcpServerDemo02 {public static void main(String[] args) throws IOException {//1.创建服务ServerSocket serverSocket=new ServerSocket(9000);//2.监听客户端的连接Socket socket=serverSocket.accept();//阻塞式监听,会一直等待客户端连接//3.获取输入流InputStream is=socket.getInputStream();//4.文件输出FileOutputStream fos=new FileOutputStream(new File("receive.png"));byte[] buffer=new byte[1024];int len;while ((len=is.read(buffer))!=-1){fos.write(buffer,0,len);}//通知客户端接收完毕了OutputStream os = socket.getOutputStream();os.write("我接收完毕了,你可以断开了".getBytes());//5.关闭资源fos.close();is.close();socket.close();serverSocket.close();}}
package reflect;import java.io.*;import .InetAddress;import .Socket;//客户端public class TcpClientDemo02 {public static void main(String[] args) throws Exception {//1.创建一个Socket连接Socket socket=new Socket(InetAddress.getByName("127.0.0.1"),9000);//2.创建一个输出流OutputStream os=socket.getOutputStream();//3.读取文件FileInputStream fis=new FileInputStream(new File("tx.png"));//4.写入文件byte[] buffer=new byte[1024];int len;while ((len=fis.read(buffer))!=-1){os.write(buffer,0,len);}//通知服务器,我已经结束了socket.shutdownOutput(); //我已经传输完了!//确定服务端接收完毕,才能够断开连接InputStream inputStream=socket.getInputStream();//String byte[]ByteArrayOutputStream baos=new ByteArrayOutputStream();byte[] buffer2=new byte[];int len2;while ((len2=inputStream.read(buffer2))!=-1){baos.write(buffer2,0,len2);}System.out.println(baos.toString());//5.关闭资源baos.close();inputStream.close();fis.close();os.close();socket.close();}}