我正在尝试编写一种方法,通过3G网络向服务器发送带有基站的消息。 IM尝试多次发送消息,直到我决定停止。但是当我测试它时,它总是在短时间后停止并停止发送消息。谁知道为什么?
private Runnable commRunnable = new Runnable() {
public void run() {
try {
String message = "Just saying hello!";
PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())), true);
String startReceivingMessage = "Begin sending me data.";
String stopReceivingMessage = "Stop sending me data.";
startSend = false;
stopSend = false;
startReceive = false;
stopReceive = false;
while (!shouldDisconnect) {
if (startSend) {
sendData = true;
startSend = false;
}
if (stopSend) {
sendData = false;
stopSend = false;
}
// Send a message that the server should start transmitting data
// back to us. We only need to transmit this message once.
if (startReceive) {
out.println(startReceivingMessage);
startReceive = false;
receiveData = true;
Thread receiveThread = new Thread(receiveRunnable);
receiveThread.start();
// Tell the server to stop transmitting data.
} else if (stopReceive) {
out.println(stopReceivingMessage);
stopReceive = false;
receiveData = false;
}
if (sendData) {
out.println(message);
}
Thread.sleep(20);
}
} catch (Exception e) {
Log.e("PowerMonitor", e.toString());
} finally {
try {
socket.close();
connected = false;
} catch (Exception e) {
Log.e("PowerMonitor", e.toString());
}
}
}
};
private Runnable receiveRunnable = new Runnable() {
@Override
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String reply = "";
Log.d("PowerMonitor", "Starting to receive");
while (receiveData) {
Log.d("PowerMonitor", "Listening...");
reply = in.readLine();
Log.d("PowerMonitor", "Got message: " + reply);
}
} catch (Exception e) {
Log.e("PowerMonitor", e.toString());
}
}
};
答案 0 :(得分:0)
我们需要更多代码才能更好地理解您的问题,但是从您在此处发布的代码看来,套接字正在被
关闭socket.close();
在finally
块中调用。
还要说明你遇到的任何错误。