套接字通信可作为Python客户端,但不能作为Java客户端

时间:2019-06-25 08:13:23

标签: java python sockets kotlin tcp

我正在尝试将套接字实现从Python改编为Java / Kotlin。我发送的命令旨在使设备 beep ,但是当我将代码转换为Java时,该命令不起作用。

我尝试将代码转换为字节数组和字符串,但两者均无效。除了设备发出蜂鸣声外,应该没有其他响应,所以我只尝试使用输出流(对于Java)。

我注意到Python版本中有一个转义字符“ \ a”,当我直接将命令复制到Java时,这给了我一个错误。我发现Python中的“ \ a”应该等效于Java中的“ \ u0007”,因此我尝试了一下,但也没有响应。

这是有效的Python实现。

from socket import socket


def main():
    print("Attempting to get response")


def beep():
    print("Beeping")
    #\a11NBB100 4000\r //buzz for 1 second at 4kHz
    sock = socket()
    sock.connect(("10.10.102.191", 8070))
    ctype = '\a11NBB100 4000\r\n'
    sock.send(ctype)
    sock.close()

if __name__ == '__main__':
    main()
    beep()

这是无效的Java实现。为此,从“主活动”中将IP作为参数传递。

package com.example.myapplication;

import android.os.AsyncTask;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

class ServerConnection extends AsyncTask<String, Void, Void> {

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

        Log.d("Socket","Connecting with IP: "+params[0]);
        String ipAdd = params[0];
        String message = "\u00071011NBB100 4000\r\n";

        try {
            // Both attempts do not work and just result in socket timeout
            sendAsBytes(ipAdd, message);
            sendAsString(ipAdd, message);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    // Try sending as Byte Array
    private void sendAsBytes(String ipAdd, String msg) throws IOException {
        Log.d("Socket", "Trying to send command " + msg + " as Byte Data");
        Socket socket = new Socket(ipAdd, 8070);
        Log.d("Socket","Connected");
        BufferedOutputStream byteOut = new BufferedOutputStream(socket.getOutputStream());
        byteOut.write(msg.getBytes());
        byteOut.flush();
        socket.close();
        Log.d("Socket", "Closed Socket");
    }

    // Try sending as String
    private void sendAsString(String ipAdd, String msg) throws IOException {
        Log.d("Socket", "Trying to send command " + msg + " as a String");
        Socket socket = new Socket(ipAdd, 8070);
        Log.d("Socket","Connected");
        PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
        printWriter.write(msg);
        printWriter.flush();
        printWriter.close();
        socket.close();
        Log.d("Socket", "Closed Socket");

    }
}

该套接字能够同时连接Python版本和Java版本,但是从Java版本发送的命令似乎无法被设备识别,而Python版本会发出 beep 声音。

0 个答案:

没有答案