Java 基于tcp协议实现文件上传
程序员文章站
2022-09-17 14:43:43
服务端package lesson02;import java.io.*;import java.net.serversocket;import java.net.socket;/** * 服务端接收...
服务端
package lesson02; import java.io.*; import java.net.serversocket; import java.net.socket; /** * 服务端接收文件 */ public class tcpserverdemo2 { 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.jpg")); 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 lesson02; import java.io.*; import java.net.inetaddress; import java.net.socket; /** * 客户端上传文件 */ public class tcpclientdemo2 { public static void main(string[] args) throws exception { //1、创建一个socket连接 socket socket = new socket(inetaddress.getbyname("127.0.0.1"), 90000); //2、创建一个输出流 outputstream os = socket.getoutputstream(); //3、读取文件 fileinputstream fis = new fileinputstream(new file("toux.jpg")); //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(); //sting byte[] bytearrayoutputstream baos = new bytearrayoutputstream(); byte[] buffer2 = new byte[1024]; int len2; while ((len2 = inputstream.read(buffer2)) != -1){ baos.write(buffer2, 0, len2); } system.out.println(baos.tostring()); //5、关闭资源 fis.close(); os.close(); socket.close(); } }
以上就是java 基于tcp协议实现文件上传的详细内容,更多关于java 文件上传的资料请关注其它相关文章!
下一篇: python 实现表情识别