Android 应用程序 - 从服务器发送和接收数据时出现问题

Android app - problem with send and receive data from server

我有问题 - 我用客户端 - 服务器通信编写应用程序(从服务器发送和接收数据),当我尝试将数据发送到服务器(或读取,冷漠地)时,应用程序关闭“应用程序保持停止”。

我使用 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();
    }
}

}

我的主要代码在 kotlin 中。我在 class“MyAp:AppCompatActivity()..”中写了“fun readSend”:

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

我在移动“seekBar”时使用它:

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

            readSend()
        }

你有什么想法,可能是什么问题? 应用程序正在编译,并且 运行,但是当我尝试移动 seekBar 时,它关闭了。有了服务器一切正常

可能是因为您试图在UI线程中进行网络操作。 尝试将套接字操作移动到另一个线程。

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