温馨提示×

温馨提示×

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

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

JavaTCP上传图片代码实例

发布时间:2020-10-21 03:02:08 来源:脚本之家 阅读:103 作者:凌晨两点半的太阳v 栏目:编程语言

1.客户端代码

public class UploadPicClient {
 public static void main(String[] args) throws UnknownHostException, IOException {
 // TODO Auto-generated method stub
 //1,创建客户端socket
 Socket s = new Socket("localhost",10088);
 //2,读取客户端要上传的图片文件
 FileInputStream fis = new FileInputStream("D:\\workspace\\day2019.1.17\\lanjing.jpg");
 //3,获取Socket输出流,将读到的图片的数据发送到服务端
 OutputStream out = s.getOutputStream();
 byte[] buf = new byte[1021];
 int len =0;
 while((len=fis.read(buf))!=-1){
  out.write(buf,0,len);
 }
 //告诉服务端说:这边的数据发送完毕让服务端停止读取
 s.shutdownOutput();
 //读取服务端发回的内容
 InputStream in = s.getInputStream();
 byte[] bufIn = new byte[1024];
 int lenIn = in.read(buf);
 String text = new String (buf,0,lenIn);
 System.out.println(text);
 //关闭资源
 fis.close();
 s.close();
 }
}

2.服务端代码

public class UploadPicSever {
public static void main(String[] args) throws IOException {
 // TODO Auto-generated method stub
 //创建tcp的socket服务端
 ServerSocket ss = new ServerSocket(10088);
 //获取客户端
 Socket s = ss.accept();
 String ip = s.getInetAddress().getHostAddress();
 System.out.println(ip+".....connected");
 //读取客户端发来的数据
 InputStream in = s.getInputStream();
 //将读取到的数据存储到一个文件中。
 File dir = new File("D:\\workspace\\day2019.1.17");
 if(!dir.exists()){
 dir.mkdirs();
 }
 File file = new File(dir,"blue.jpg");
 FileOutputStream fos = new FileOutputStream(file);
 byte[] buf = new byte[1024];
 int len = 0;
 while ((len=in.read(buf))!=-1){
 fos.write(buf,0,len);
 }
 //获取socket输出流,将上传成功字样发送给客户端
 OutputStream out = s.getOutputStream();
 out.write("上传成功".getBytes());
 fos.close();
 s.close();
 ss.close();
}

上传后和上传前的图片:

JavaTCP上传图片代码实例

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对亿速云的支持。如果你想了解更多相关内容请查看下面相关链接

向AI问一下细节

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

AI