欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 产业 > JAVA客户端发送图片给服务端案例

JAVA客户端发送图片给服务端案例

2024/10/25 18:33:42 来源:https://blog.csdn.net/qq_61033357/article/details/142363687  浏览:    关键词:JAVA客户端发送图片给服务端案例

文章目录

      • 1.客户端发送图片给服务端案例(TCP为例)

1.客户端发送图片给服务端案例(TCP为例)

客户端

public void client() throws IOException {// 1.创建Socket// 指明服务器端的IP地址和端口号InetAddress inetAddress = InetAddress.getByName("192.168.199.191"); // inetAddress变量将存储这个IP地址的封装对象。你可以使用这个InetAddress对象执行网络相关的操作,比如获取IP地址、主机名等信息。int port = 8989;Socket socket = new Socket(inetAddress, port);//2.创建File实例,FileInputStreamFile file = new File("image.png");FileInputStream fis = new FileInputStream(file);//3.通过Socket,获取输出流OutputStream os = socket.getOutputStream();// 读写数据byte[] buffer = new byte[1024];int len;while((len = fis.read(buffer)) != -1){os.write(buffer, 0, len);}System.out.println("数据发送完毕");//4.关闭Socket和相关的流os.close();fis.close();socket.close();}

服务端

@Testpublic void server() throws IOException {// 1.创建ServerSocketint port = 8989;ServerSocket serverSocket = new ServerSocket(port);// 2.接受来自于客户端的socketSocket socket = serverSocket.accept();// 3.通过Socket获取输入流InputStream is = socket.getInputStream();// 4.创建File类的实例,FileOutputStream实例File file = new File("image_111.png");FileOutputStream fos = new FileOutputStream(file);// 5.读写过程byte[] buffer = new byte[1024];int len;while((len = is.read(buffer)) != -1){fos.write(buffer, 0, len);}System.out.println("数据接收完毕");// 6.关闭相关的socket和流fos.close();is.close();socket.close();}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com