Android Socket Image

package com.example.qing.socketsendimage;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

public class MainActivity extends AppCompatActivity {
    Button sendImage;
    ImageView imageview;
    public void sendTextMsg(DataOutputStream out, String msg) throws IOException {
        byte[] bytes = msg.getBytes();
        long len = bytes.length;
        //先发送长度,在发送内容
        out.writeLong(len);
        out.write(bytes);
    }
    public void sendImgMsg(DataOutputStream out ) throws IOException {
        //发送的图片为图标,就是安卓机器人,将bitmap转为字节数组
        Log.i("sendImgMsg", "len: "+"1");
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
//        imageview.setImageBitmap(bitmap);

        Log.i("sendImgMsg", "len: "+"2");
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG,80,bout);
        //写入字节的长度,再写入图片的字节
        long len = bout.size();
        //这里打印一下发送的长度
        Log.i("sendImgMsg", "len: "+len);
        out.writeLong(len);
        out.write(bout.toByteArray());
    }

    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sendImage=(Button)findViewById(R.id.buttonSend);
        imageview=(ImageView)findViewById(R.id.image1);

        sendImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                imageview.setImageResource(R.mipmap.ic_launcher);
                new Thread() {
                    Socket socket;
                    String host="192.168.91.1";
                    int post=8999;
                    public void run() {
                        try {
                            //建立连接
                            socket = new Socket(host, post);
                            //获取输出流,通过这个流发送消息
                            DataOutputStream out = new DataOutputStream(socket.getOutputStream());
                            //发送文字消息
//                            sendTextMsg(out,"来自手机客户端的消息");
                            sendImgMsg(out);
                            out.close();
                            socket.close();

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    //启动线程
                }.start();



            }
        });

    }

}
package listspackage;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.SQLException;
import java.util.Base64;
public class Service {
    private static Socket socket;
  //定义端口号
    private static final int POST = 8999;

    public static void main(String[] args) {
        try {
          //接收消息
            getMsg();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void getMsg() throws IOException {
        System.out.println("开始连接");
        ServerSocket serverSocket = new ServerSocket(POST);
        Socket socket = serverSocket.accept();
      //获取输入流,通过这个流来读取消息
        DataInputStream input = new DataInputStream(socket.getInputStream());
        
        //接收文字消息
//        getTextMsg(input);
        getImgMsg(input);
        input.close();
        socket.close();
        serverSocket.close();
        System.out.println("通讯结束");
    }
    
    public static void getImgMsg(DataInputStream input) throws IOException {
  	  //同样是先读长度
    	System.out.println("ok");
  	    long len = input.readLong();
  	    System.out.println("len = " + len);
  	    byte[] bytes = new byte[(int) len];
  	  //然后在读这个长度的字节到字节数组
  	    input.readFully(bytes);
  	  //将独到的内容保存为文件到本地
  	    File file = new File("C:\\Users\\Administrator\\Desktop\\" + len + ".png");
  	    FileOutputStream fileOutputStream = new FileOutputStream(file);
  	    fileOutputStream.write(bytes);
  	    System.out.println("ok");
  	}

    public static String getTextMsg(DataInputStream input) throws IOException {
      //一样先读长度,再根据长度读消息
        long len = input.readLong();
        System.out.println("len = " + len);
        byte[] bytes = new byte[(int) len];
        input.read(bytes);
        String msg = new String(bytes);
        System.out.println("msd = " + msg);
        return msg;
    }
}

 

### 回答1: Android使用Socket进行图片互传的实例可以按照以下步骤进行: 1. 在发送端(Client端)中,首先创建一个Socket对象,并指定服务器的IP地址和端口号。 2. 创建一个用于获取图片的输入流,并将图片数据读取到内存中。 3. 通过Socket的输出流将图片数据发送给服务器。 4. 在接收端(Server端)中,创建一个ServerSocket对象,并指定监听的端口号。 5. 循环等待客户端的连接请求,当有客户端连接时,接受到客户端的Socket对象。 6. 创建一个用于接收图片的输出流,将从客户端接收到的图片数据写入到指定文件中。 7. 当图片数据传输完成后,关闭Socket和ServerSocket对象。 具体的代码实现如下所示: 发送端: ```java try { // 创建客户端Socket,指定服务器IP地址和端口号 Socket clientSocket = new Socket("服务器IP地址", 端口号); // 获取图片文件的输入流 InputStream inputStream = new FileInputStream("图片文件路径"); // 创建Socket的输出流 OutputStream outputStream = clientSocket.getOutputStream(); // 定义一个字节数组用于保存图片数据 byte[] buffer = new byte[1024]; int len; // 从输入流中读取图片数据并发送给服务器 while ((len = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, len); } // 关闭输入流、输出流和Socket连接 inputStream.close(); outputStream.close(); clientSocket.close(); } catch (IOException e) { e.printStackTrace(); } ``` 接收端: ```java try { // 创建服务器端的ServerSocket,指定监听端口号 ServerSocket serverSocket = new ServerSocket(端口号); // 等待客户端的连接请求 Socket clientSocket = serverSocket.accept(); // 创建用于接收图片的输出流 OutputStream outputStream = new FileOutputStream("保存图片的路径"); // 获取客户端Socket的输入流 InputStream inputStream = clientSocket.getInputStream(); // 定义一个字节数组用于保存图片数据 byte[] buffer = new byte[1024]; int len; // 从输入流中读取图片数据并写入到文件中 while ((len = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, len); } // 关闭输入流、输出流和Socket连接 inputStream.close(); outputStream.close(); clientSocket.close(); serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } ``` 以上就是使用Socket进行Android图片互传的简单示例。你可以根据实际需求,在发送端和接收端的代码中做相应的修改和扩展。 ### 回答2: Android使用Socket进行图片互传是一种常见的网络通信方式。下面以客户端和服务器端的实例介绍其具体使用方法。 服务端: 1. 创建一个服务器端的Socket对象,并指定监听的端口号。 2. 使用ServerSocket的accept()方法监听客户端连接请求,并获取客户端的Socket对象。 3. 通过InputStream读取客户端发来的图片数据。 4. 将接收到的图片数据保存到本地。 客户端: 1. 创建一个客户端的Socket对象,并指定服务端的IP地址和端口号。 2. 使用OutputStream发送图片数据到服务器端。 3. 关闭Socket。 以上是一个简单的图片传输的示例,具体的实现过程中还可以增加异常处理和代码优化。另外,图片的传输还可以使用HTTP协议,通过在请求头中添加Content-Type字段来传输图片。在服务端,可以使用HTTP服务器框架如Spring Boot等来接收和处理请求,并将图片保存到本地。 总结:使用Socket进行图片互传是一种基于TCP/IP协议的通信方式,通过在服务端和客户端之间建立Socket连接,并传输图片数据实现互传功能。在具体的实现过程中,要注意代码的健壮性和异常处理,以确保通信的稳定和准确。 ### 回答3: android使用socket进行图片互传实例的步骤如下: 1. 创建一个Socket服务器端和一个Socket客户端,通过TCP连接两者之间的通信。 2. 服务器端创建一个ServerSocket来监听客户端的连接请求。 3. 当客户端连接至服务器时,服务器端接受该连接并创建一个Socket对象。 4. 服务器端读取图片文件,并将其转换为字节数组。 5. 服务器端使用Socket的输出流将字节数组发送给客户端。 6. 客户端接收到服务器端发送的字节数组,将其转换为图片文件。 7. 客户端保存接收到的图片文件,并在界面上显示出来。 以下是一个简单的Android使用Socket进行图片互传的示例代码: 服务器端代码: ``` try { // 创建ServerSocket监听指定端口 ServerSocket serverSocket = new ServerSocket(8888); // 等待客户端连接 Socket socket = serverSocket.accept(); // 读取图片文件并转换为字节数组 File file = new File("/path/to/image.jpg"); FileInputStream fileInputStream = new FileInputStream(file); byte[] buffer = new byte[(int) file.length()]; fileInputStream.read(buffer); // 发送字节数组给客户端 OutputStream outputStream = socket.getOutputStream(); outputStream.write(buffer); // 关闭连接 outputStream.flush(); outputStream.close(); fileInputStream.close(); socket.close(); serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } ``` 客户端代码: ``` try { // 创建与服务器连接的Socket Socket socket = new Socket("服务器IP地址", 8888); // 读取字节数组并转换为图片文件 InputStream inputStream = socket.getInputStream(); byte[] buffer = new byte[1024]; int bytesRead; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); while ((bytesRead = inputStream.read(buffer)) != -1) { byteArrayOutputStream.write(buffer, 0, bytesRead); } byte[] imageBytes = byteArrayOutputStream.toByteArray(); // 将字节数组转换为图片文件并保存 Bitmap bitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length); File file = new File("/path/to/save/image.jpg"); FileOutputStream fileOutputStream = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream); // 关闭连接 fileOutputStream.close(); inputStream.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } ``` 以上是一个基本的Android使用Socket进行图片互传的示例。通过服务器端将图片转换为字节数组并发送给客户端,客户端接收到字节数组后将其转换为图片文件并保存。具体实现可根据项目需求进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值