700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > TCP:利用Socket编程技术实现客户端向服务端上传一个图片。

TCP:利用Socket编程技术实现客户端向服务端上传一个图片。

时间:2020-05-15 19:32:39

相关推荐

TCP:利用Socket编程技术实现客户端向服务端上传一个图片。

问题:

利用Socket编程技术实现客户端向服务端上传一个图片的程序。

客户端:

import java.io.*;import .Socket;public class client{public static byte[] getimg(String imgpath) throws IOException{FileInputStream img = new FileInputStream(imgpath); //读取图片的字节流ByteArrayOutputStream out = new ByteArrayOutputStream();byte[] res = new byte[1024];int num = 0;while ((num = img.read(res)) != -1){out.write(res, 0, num); //写入}return out.toByteArray();}public static void main(String[] args) throws IOException{Socket s = new Socket("127.0.0.1", 10000);OutputStream out = s.getOutputStream();byte[] a = getimg("E:\\1.jpg"); //得到图片的字节数组out.write(a); //写入s.close();out.close();}}

服务端:

import java.io.*;import .ServerSocket;import .Socket;public class server{public static void main(String[] args) throws IOException{ServerSocket now = new ServerSocket(10000);Socket s = now.accept();InputStream in = s.getInputStream();ByteArrayOutputStream out = new ByteArrayOutputStream();int tr;byte[] u = new byte[1024];while ((tr = in.read(u)) != -1){out.write(u, 0, tr); //写入out}FileOutputStream fileout = new FileOutputStream("E:\\2.jpg");fileout.write(out.toByteArray()); //写入图片文件out.close();}}

实验结果:

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。