jelly_lzy
2018-05-25 07:34
采纳率: 0%
浏览 606

各位大神好,请教一个android socket的问题

我目前遇到的问题是这样的:我想实现的功能是PC通过USB线连接到android手机,然后PC作为客户端,手机作为服务端,然后进行socket通信,我实现了一种方法,PC端使用
Java来写,已经成功了,现在我需要PC端需要python来写,就是说PC端用python实现
socket的客户端与手机进行USB通信;目前我也实验的差不多了,但是有个问题是:PC端能够连上服务端,但是数据似乎发布出去,安卓手机端一直卡在readUTF()的地方,但是安卓端可以给PC端回数据,PC端也能接收到android端的数据,附上代码,求大神?
PC python 客户端:(我PC端使用了adb forward端口转发)

import socket
import os
from time import sleep
from logging import shutdown
host='127.0.0.1'
port=9000

os.system("adb forward tcp:9000 tcp:9000")
sleep(3)

while 1:
    try:
        cmdstr=raw_input("please input cmd:")
        s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        s.connect((host,port))
        print "connect success"
        #s.sendall("asdafaf")
        #s.settimeout(10)

        req_msg = b'host:transport-any'
        s.sendall('%04x' % len(req_msg))
        s.sendall(req_msg)
        #s.settimeout(10)

        print "send ok"
        data=s.recv(1024)
        print data

    except:
        os.system('adb start-server')
        sleep(2)
        continue


    os.system("pause")

    #s.shutdown(2)
    #s.close()

android 服务端

package com.example.server_android;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;
import android.util.Log;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class MainActivity extends Activity {

    private static final String TAG = "ServerThread";

    ServerThread serverThread;

    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            Toast.makeText(getApplicationContext(), msg.getData().getString("MSG", "Toast"), Toast.LENGTH_SHORT).show();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        serverThread = new ServerThread();
        serverThread.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        serverThread.setIsLoop(false);
    }

    class ServerThread extends Thread {

        boolean isLoop = true;

        public void setIsLoop(boolean isLoop) {
            this.isLoop = isLoop;
        }

        @Override
        public void run() {
            Log.d(TAG, "running");

            ServerSocket serverSocket = null;
            try {
                serverSocket = new ServerSocket(9000);

                while (isLoop) {
                    Socket socket = serverSocket.accept();

                    Log.d(TAG, "accept");

                    DataInputStream inputStream = new DataInputStream(socket.getInputStream());
                    String msg = inputStream.readUTF();
                    Log.d(TAG, "Message:"+msg);


                    DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
                    outputStream.writeUTF("Receive OK");
                    outputStream.flush();

                    //jelly test begin

                    //outputStream.writeUTF("Receive OK\r");

                    //jelly test end

                    Message message = Message.obtain();
                    Bundle bundle = new Bundle();
                    bundle.putString("MSG", msg);
                    message.setData(bundle);
                    handler.sendMessage(message);

                    socket.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                Log.d(TAG, "destory");

                if (serverSocket != null) {
                    try {
                        serverSocket.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

}

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • 最爱吃葡萄 2018-05-25 08:21

    python 传递 的数据是UTF编码吗?会不会是编码问题?

    打赏 评论
  • jelly_lzy 2018-05-25 09:43

    应该就是编码的问题,但是在python端我怎么修改都无法成功,android端不管怎样都接收不到,我最后找到一个方法是python端不用改,改了下android端的代码,如下,有遇到和我一样问题的朋友可以参考下

     package com.example.server_android;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.widget.Toast;
    import android.util.Log;
    
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    public class MainActivity extends Activity {
    
        private static final String TAG = "ServerThread";
    
        ServerThread serverThread;
    
        Handler handler = new Handler() {
    
            @Override
            public void handleMessage(Message msg) {
                Toast.makeText(getApplicationContext(), msg.getData().getString("MSG", "Toast"), Toast.LENGTH_SHORT).show();
            }
        };
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            serverThread = new ServerThread();
            serverThread.start();
        }
    
        @Override
        protected void onDestroy() {
            super.onDestroy();
            serverThread.setIsLoop(false);
        }
    
        class ServerThread extends Thread {
    
            boolean isLoop = true;
    
            public void setIsLoop(boolean isLoop) {
                this.isLoop = isLoop;
            }
    
            @Override
            public void run() {
                Log.d(TAG, "running");
    
                ServerSocket serverSocket = null;
                try {
                    serverSocket = new ServerSocket(9000);
    
                    while (isLoop) {
                        Socket socket = serverSocket.accept();
    
                        Log.d(TAG, "accept");
    
                        DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
                        outputStream.writeUTF("Receive OK");
                        outputStream.flush();
    
                        InputStreamReader isr = new InputStreamReader(socket.getInputStream());
                        BufferedReader br = new BufferedReader(isr);
    
                        // 步骤3:通过输入流读取器对象 接收服务器发送过来的数据
                        String msg = br.readLine();
                        Log.d(TAG, "Message:"+msg);
    
                        //jelly test begin
    
                        //outputStream.writeUTF("Receive OK\r");
    
                        //jelly test end
    
                        Message message = Message.obtain();
                        Bundle bundle = new Bundle();
                        bundle.putString("MSG", msg);
                        message.setData(bundle);
                        handler.sendMessage(message);
    
                        socket.close();
                    }
    
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    Log.d(TAG, "destory");
    
                    if (serverSocket != null) {
                        try {
                            serverSocket.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    
    }
    
    
    打赏 评论
  • lwl8851206 2018-05-25 11:50

    不需要,直接重置就好

    打赏 评论

相关推荐 更多相似问题