[英]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):我使用 class“公共 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.我的主要代码在 kotlin 中。 I wrote "fun readSend" in class "MyAp: AppCompatActivity()..":
我在 class “MyAp: AppCompatActivity()..”中写了“有趣的 readSend”:
fun readSend(){
val nc = NetClient("192.168.2.12", 7800)
nc.sendDataWithString("my data")
}
and i use it, when i move "seekBar":我使用它,当我移动“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.
应用程序正在编译并运行,但是当我尝试移动 seekBar 时,它关闭了。 With server all is ok.
使用服务器一切正常。
May be because you are trying to perform network operation in the UI thread.可能是因为您试图在 UI 线程中执行网络操作。 Try moving socket operations to another thread.
尝试将套接字操作移动到另一个线程。
Thread t = new Thread() {
public void run() {
readSend();
}
}.start();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.