Android supports open socket stream connection

Thank you for your help.

I am trying to transfer sensor data from my Android device to a server through a TCP socket. I'm new to Android, and threads are a complicated concept to understand.

I have two methods: connectToServer () and sendDataToServer (). connectToServer () is called once at startup, and sendDataToSever () is called again and again at about 100 Hz. I would like to open the socket on connectToServer () and always leave it open, so sendDataToServer () can re-send data to this socket.

public static void connectToServer(){
    sendThread = new Thread(new Runnable() {
        public void run() {
            mySocket = null;
            os = null;
            try {
                mySocket = new Socket(PC_IP, PORT);
                os = new DataOutputStream(mySocket.getOutputStream());
            } catch (UnknownHostException exception) {
                Log.d("sunnyDay", exception.getMessage());
            } catch (IOException exception) {
                Log.d("sunnyDay", exception.getMessage());
            }
        }
    });
    sendThread.start();
}


public static void sendDataToServer(byte[] data) {

    String dataString = Arrays.toString(data);

    // send this String to the server
    sendThread = new Thread(new Runnable() {
        public void run() {
            if (mySocket != null && os != null) {
                try {
                    os.writeBytes(dataString + "\n");
                }  catch (IOException exception) {
                    Log.d("sunnyDay", exception.getMessage());
                }
            }
        }
    });
    sendThread.start();
}

The only way I could resend the data was to close and reopen the socket every time in one thread call, although I feel this is not a solution.

, , , , - .

.

!

+4
1

os.flush() os.writeBytes(dataString + "\n" );

+1

Source: https://habr.com/ru/post/1685802/


All Articles