Android keep socket connection open on thread

364
September 17, 2017, at 08:51 AM

thank you for your help.

I'm trying to stream sensor data from my android device to a server via TCP socket. I'm fairly new to Android and threads are a tough concept for me to grasp.

I have two methods, connectToServer() and sendDataToServer(). connectToServer() is called once at startup and sendDataToSever() is called over and over again at about 100 HZ. I would like to open the socket at connectToServer() and leave it open always, so that sendDataToServer() can send data on that socket repeatedly.

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've been able to repeatedly send data is by closing and reopening the socket every time in the same thread call, although I feel like this is not the solution.

I tried to have them both on the same thread so that the socket connection is still there, I'm assuming this is where I'm missing something about threads.

Any input is greatly appreciated.

Thanks!

Answer 1

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

Rent Charter Buses Company
READ ALSO
interfacing with raspberry pi gpio [on hold]

interfacing with raspberry pi gpio [on hold]

I need some helpI am trying to write java code to work on a pi to check the status of a pin in the gpio

281
How do I reflect changes made in one list onto another?

How do I reflect changes made in one list onto another?

Essentially what I'm trying to do is have a backing list which gets all the changes reflected to it from other "sublists"To be more elaborate, here's what I'm trying to do:

222
Java class fields, object use in Beanshell

Java class fields, object use in Beanshell

I am using Java with JSF and Beanshell scriptI want to use fields and object of java class in beanshell

386