欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python/java 通过socket 访问Android进行通信

程序员文章站 2022-03-24 11:45:58
...

 

最近因为业务上面需要,需要建立在Android中建立Socket服务端,在PC端通过ADB工具访问服务器端进行通信。在网上参考了多个例子后,参照代码写了一个简单的demo,仅此记录一下。希望对大家有抛砖引玉的作用。

Android服务端,采用多线程的方式,单独启动一条线程对Socket进行监听收到消息后进行相应的处理。

由于需要进行网络连接,Android的AndroidManifest.xml需要开通对应的权限

<uses-permission android:name="android.permission.INTERNET"/>

SocketTestThread.java

public class SocketTestThread extends Thread{

    private BufferedOutputStream output;    //输出流
    private BufferedInputStream input;      //输入流
    private Socket socket;
    private static String TAG="SocketTestThread";

    @Override
    public void run() {
        try {
            ServerSocket serverSocket = new ServerSocket(9000);
            while (true) {
                Log.d(TAG, "等待来自pc端的数据...端口9000");
                socket = serverSocket.accept();
                output=new BufferedOutputStream(socket.getOutputStream());
                input=new BufferedInputStream(socket.getInputStream());
                Log.d(TAG, "收到来自pc端的数据,以下是数据内容:");
                Log.d(TAG,readMsgFromSocket(input));
                SendMsg("你的消息我收到了,我是Android端");
                Log.d(TAG, "消息已发送,准备关闭socket");
                socket.close();
                Log.d(TAG, "Socket已经关闭");
            }
        } catch (IOException e) {
            e.printStackTrace();
            Log.e(TAG,"发生异常了,异常是:"+e.getMessage());
        }
    }


    public String readMsgFromSocket(InputStream in) {                   //读取客户端发过来的文本数据
        String msg = "";
        byte[] tempbuffer = new byte[1024];
        try {
            int numReadedBytes = in.read(tempbuffer, 0, tempbuffer.length);
            msg = new String(tempbuffer, 0, numReadedBytes, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return msg;
    }

    public void SendMsg(String msg) {                                  //发送文本数据给客户端
        String msg_1 = msg;
        try {
            output.write(msg_1.getBytes("UTF-8"));
            output.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

客户端采用java和python两种实现,仅供参考。

SocketTest.java

public class SocketTest {
    private static BufferedOutputStream output;    //输出流
    private static BufferedInputStream input;      //输入流


    public static void main(String[] args) {
        try {
            //adb 的路径
            String adbHome = "D:\\tools\\adb\\adb ";
            //adb查看版本号
            String versionCmd = adbHome + "--version";
            //pc和手机的端口转发命令,可参考:https://blog.csdn.net/u013553529/article/details/80036227
            //不执行转发的话会出现:Connection refused 异常
            String forwardCmd = adbHome + "forward tcp:8005 tcp:9000";
            //pc和手机的端口转发,两边端口号可一样也可以不一样,自行定义,不执行的话两边无法通信
            exec(forwardCmd);
            //测试读取adb版本号
            System.out.println("versionCmd: " + exec(versionCmd));
            //连接adb服务器,本地ip,也就是通过有线方式,需要手机端先开启服务器监听来自pc的socket连接
            Socket socket = new Socket("127.0.0.1", 8005);
            output=new BufferedOutputStream(socket.getOutputStream());
            input=new BufferedInputStream(socket.getInputStream());
            SendMsg("我是来自pc端java的数据");
            String msg = readMsgFromSocket(socket.getInputStream());
            System.out.println("收到来自手机端发来的数据: " + msg);
            //最后关闭socket
            socket.close();
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }
    }

    /**
     * 执行adb指令
     * @param cmd adb指令
     * @return 返回执行结果的字符串
     */
    public static String exec(String cmd){
        Process process;
        try {
            process=Runtime.getRuntime().exec(cmd);
            return InputStream2String(process.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * adb指令的InputStream转成字符串输出
     * @param inputStream adb指令inputStream
     * @return 返回执行结果的字符串
     */
    public static String InputStream2String(InputStream inputStream){
        String result="";
        BufferedReader br=new BufferedReader(new InputStreamReader(inputStream));
        try {
            String temp="";
            while ((temp=br.readLine())!=null){
                result+=temp+"\n";
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String readMsgFromSocket(InputStream in) {                   //读取客户端发过来的文本数据
        String msg = "";
        byte[] tempbuffer = new byte[1024];
        try {
            int numReadedBytes = in.read(tempbuffer, 0, tempbuffer.length);
            msg = new String(tempbuffer, 0, numReadedBytes, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return msg;
    }

    public static void SendMsg(String msg) {                                  //发送文本数据给客户端
        String msg_1 = msg;
        try {
            output.write(msg_1.getBytes("UTF-8"));
            output.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

socketTest.py

import socket
import os

def startSocket():
    os.popen("adb forward tcp:8004 tcp:9000 ")
    client_address = ('127.0.0.1', 8004)
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client_socket.connect(client_address)
    print("准备发送")
    msg = str("我是来自于Python数据")
    client_socket.send(msg.encode("UTF-8"))
    print(f"已经发送消息:{msg}")
    response = client_socket.recv(1024).decode()
    print(response)
    client_socket.close()

if __name__ == '__main__':
    startSocket()

 

参考文章:

https://blog.csdn.net/DickyQie/article/details/80045639

https://blog.csdn.net/zhou0213xy/article/details/79498708

 

 

相关标签: java Android