java - Python(服务器)从Java(客户端)接收数据在单独的行中..(TCP)

标签 java android python sockets

好吧,我读了很多问题但无法弄清楚。我遇到从 Android 应用程序收到的数据问题。基本上我想控制伺服系统。该代码有效,但应用程序发送到服务器的数据是在单独的行中接收的。是的,我知道我需要使用缓冲区,我进行了一些研究,但找不到向我的代码添加缓冲区的方法。 另外,我认为我不需要显示我的 Java 代码,因为它只是通过按钮单击发送的基本命令(向上、向下等字符串)。

...Python Code(Server)...
  ctrCmd = ['Up','Down', 'ON', 'OFF']
  ...
  ...
  while True:
        print ("Waiting for connection")
        tcpCliSock,addr = tcpSerSock.accept()
        print ("...connected from :", addr)

    try:
            while True:
                    data = ''
                    data = tcpCliSock.recv(BUFSIZE).decode()
                    print("This",data)

                    if not data:
                            print ("No Data",data)
                            break
                    if data == ctrCmd[0]:
                            print("I am here")
                            Servomotor.ServoUp()
                            print ("Increase: ",Servomotor.cur_X)
                            #tcpCliSock.send("Servo Increases".encode())
                    if data == ctrCmd[1]:
                            Servomotor.ServoDown()
                            print ("Decrease: ",Servomotor.cur_X)
                            #tcpCliSock.send("Servo Decreases".encode())
                    if data == ctrCmd[2]:
                            Servomotor.ledOn()
                            print ("Led On")
                            #tcpCliSock.send("Led On".encode())
                    if data == ctrCmd[3]:
                            Servomotor.ledOff()
                            print ("Led Off")
                           # tcpCliSock.send("Led Off".encode())
    except KeyboardInterrupt:
            Servomotor.close()
            GPIO.cleanup()
tcpSerSock.close();

enter image description here

我也不明白为什么它显示没有数据,即使它显示收到的数据? 请帮助我真的是一个菜鸟,正在努力学习。 谢谢!!

更新!! 在我更改了decode()建议后,

enter image description here

    public class MainActivity extends AppCompatActivity {
    //UI Element
    Button btnUp;
    Button btnDown;
    Button btnLedOn;
    Button btnLedOff;
    EditText txtAddress;
    /*TextView message;*/
    Socket myAppSocket = null;
    public static String wifiModuleIp = "";
    public static int wifiModulePort = 0;
    public static String CMD = "0";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnUp = (Button) findViewById(R.id.btnUp);
        btnDown = (Button) findViewById(R.id.btnDown);
        btnLedOn = (Button) findViewById(R.id.btnLedOn);
        btnLedOff = (Button) findViewById(R.id.btnLedOff);
        txtAddress = (EditText) findViewById(R.id.ipAddress);
        /*message = (TextView) findViewById(R.id.message);*/

        btnUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getIPandPort();
                CMD = "Up";
                Socket_AsyncTask cmd_increase_servo = new Socket_AsyncTask();
                cmd_increase_servo.execute();
            }
        });
        btnDown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getIPandPort();
                CMD = "Down";
                Socket_AsyncTask cmd_increase_servo = new Socket_AsyncTask();
                cmd_increase_servo.execute();
            }
        });
        btnLedOn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getIPandPort();;
                CMD = "ON";
                Socket_AsyncTask cmd_led_on = new Socket_AsyncTask();
                cmd_led_on.execute();
            }
        });
        btnLedOff.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getIPandPort();
                CMD = "OFF";
                Socket_AsyncTask cmd_led_off = new Socket_AsyncTask();
                cmd_led_off.execute();
            }
        });

    }
    public void getIPandPort()
    {
        String iPandPort = txtAddress.getText().toString();

        Log.d("MYTEST","IP String: "+ iPandPort);
        String temp[]= iPandPort.split(":");
        wifiModuleIp = temp[0];
        wifiModulePort = Integer.valueOf(temp[1]);
        Log.d("MY TEST","IP:" +wifiModuleIp);
        Log.d("MY TEST","PORT:"+wifiModulePort);
    }
    public class Socket_AsyncTask extends AsyncTask<Void,Void,Void>
    {
        Socket socket;

        @Override
        protected Void doInBackground(Void... params){

            try{

                InetAddress inetAddress = InetAddress.getByName(MainActivity.wifiModuleIp);
                socket = new java.net.Socket(inetAddress,MainActivity.wifiModulePort);
                //read input msg from server

                DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
                dataOutputStream.writeBytes(CMD);
                System.out.println(CMD);
                dataOutputStream.close();

                socket.close();
            }catch (UnknownHostException e){e.printStackTrace();}catch (IOException e){e.printStackTrace();}
            return null;
        }
    }
}

Android 代码的输出 enter image description here

5 月 17 日更新 我尝试 writeUTF 它在 Up 之前给出了一些空数据(参见图片) enter image description here

最佳答案

尝试一下:

socket = new java.net.Socket(inetAddress,MainActivity.wifiModulePort);
//read input msg from server
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeChars(CMD);
System.out.println(CMD);
dataOutputStream.close();

socket.close();

如果这会增加额外的空格,那么最简单的解决方案是继续使用 writeutf 并在服务器端对数据进行子串

socket = new java.net.Socket(inetAddress,MainActivity.wifiModulePort);

//read input msg from server
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeUTF(CMD);
System.out.println(CMD);
dataOutputStream.close();

socket.close();

在服务器端:

data = tcpCliSock.recv(BUFSIZE).decode()
data = data[2:]

引自 Javadoc:

Writes a string to the underlying output stream using modified UTF-8 encoding in a machine-independent manner.

First, two bytes are written to the output stream as if by the writeShort method giving the number of bytes to follow. This value is the number of bytes actually written out, not the length of the string. Following the length, each character of the string is output, in sequence, using the modified UTF-8 encoding for the character. If no exception is thrown, the counter written is incremented by the total number of bytes written to the output stream. This will be at least two plus the length of str, and at most two plus thrice the length of str.

关于java - Python(服务器)从Java(客户端)接收数据在单独的行中..(TCP),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56146955/

相关文章:

java - 如何从 HttpEntity Java 中仅获取 Json 内容

java.lang.NoClassDefFoundError : com. google.ads.AdView

Android填写路径的一部分?

java - 使用 java.lang.Runtime.getRuntime 在 matlab 中调用多个 python 脚本实例不起作用

java - Swing 容器和组件之间的父子关系

c++ - 移动设备的最佳加密库?

java - OpenGL ES 渲染错误

python - Matplotlib 具有转换值的第二个 x 轴

python - pip:找不到与 tensorflow 匹配的分布

python - 使用 Fortran 求解器在 Windows 64 位上安装 Odespy