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();}