0

我正在尝试编写一种方法,该方法将通过带有基站的 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());
        }
    }
};
4

1 回答 1

0

我们需要您的更多代码才能更好地理解您的问题,但是从您在此处发布的代码看来,套接字似乎被

socket.close();

finally块中调用。还要告诉您遇到的任何错误。

于 2012-07-04T09:07:41.980 回答