温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java 网络编程-TCP-上传文件

发布时间:2020-09-10 17:34:54 来源:网络 阅读:319 作者:wx5d21d5e6e5ab1 栏目:编程语言

Socket 的输入输出流只在服务器和客户端之间运输,所以需要额外的字节流读取文件内容然后Socket流写入,保存时,服务器端的Socket流读取的时候额外的字节流写出到文件

客户端: 上传文件

public class tcp2 { public static void main(String[]args) throws IOException { System.out.println("客户端启动中"); Socket client =new Socket("localhost",8888); //文件的拷贝 InputStream is=new BufferedInputStream(new FileInputStream("src\\linux学习路线.png")); OutputStream os=new BufferedOutputStream(client.getOutputStream()); byte[] data=new byte[1024*60]; int len=-1; while((len=is.read(data))!=-1) { os.write(data,0,len); } os.flush(); os.close(); client.close(); } }

服务器端:存储文件

public class tcp { public static void main(String[]args) throws IOException { System.out.println("服务器启动中..."); ServerSocket server=new ServerSocket(8888); Socket client=server.accept(); //文件的拷贝 InputStream is=new BufferedInputStream(client.getInputStream()); OutputStream os=new BufferedOutputStream(new FileOutputStream("D:/d/tu.jpg")); byte[] flush=new byte[1024*60]; int len=-1; while((len=is.read(flush))!=-1) { os.write(flush,0,len); } is.close(); os.close(); client.close(); } }
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI