Search code examples
javaandroidkotlinserverclient

Android app - problem with send and receive data from server


I have problem - i wrote app with client - server comunication (send and receive data from server), and when i try send data to server (or read, indifferently ) the application closes "app keep stopping".

I use class "public class NetClient" (java):

public NetClient(String host, int port) {
    this.host = host;
    this.port = port;
}

private void connectWithServer() {
    try {
        if (socket == null) {
            socket = new Socket(this.host, this.port);
            out = new PrintWriter(socket.getOutputStream());
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private void disConnectWithServer() {
    if (socket != null) {
        if (socket.isConnected()) {
            try {
                in.close();
                out.close();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

public void sendDataWithString(String message) {
    if (message != null) {
        connectWithServer();
        out.write(message);
        //out.flush();
    }
}

public String receiveDataFromServer() {
    try {
        String message = "";
        int charsRead = 0;
        char[] buffer = new char[BUFFER_SIZE];

        while ((charsRead = in.read(buffer)) != -1) {
            message += new String(buffer).substring(0, charsRead);
        }

        disConnectWithServer(); // disconnect server
        return message;
    } catch (IOException e) {
        return "Error receiving response:  " + e.getMessage();
    }
}

}

My main code is in kotlin. I wrote "fun readSend" in class "MyAp : AppCompatActivity().." :

    fun readSend(){
        val nc = NetClient("192.168.2.12", 7800)
        nc.sendDataWithString("my data")
    }

and i use it, when i move "seekBar":

        seekBarVelocity.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
        override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
            resultsTextVelocity.text = "Vel.: " + progress.toString() + "%"

            readSend()
        }

Do you have any idea, what could be the problem? App is compiling, and run, but when i try move seekBar, it close. With server all is ok.


Solution

  • May be because you are trying to perform network operation in the UI thread. Try moving socket operations to another thread.

     Thread t = new Thread() {
         public void run() {
             readSend();
         }
     }.start();