簡體   English   中英

Android套接字已連接但不發送數據

[英]Android socket is connected but doesn't send data

我正在開發一個Android客戶端應用程序,通過普通的TCP Socket與服務器通信,我們假設服務器IP 192.168.1.2和androdi設備IP是192.168.1.3。

我打開套接字,我檢查套接字是否已連接(我的結果是真的)然后我寫了一個演示文稿消息。

這是我的代碼

// scoket setup
Sockets = new Socket(addressToConnect, 2015);
s.setSoTimeout(2500);
setTcpNoDelay(true);

// if i'm connected
if (s.isConnected()) {
    // wrapping streams
    DataInputStream dis = new DataInputStream(s.getInputStream());
    DataOutputStream dos = new DataOutputStream(s.getOutputStream());

    // sending data
    String presentationMessage = "Presentation message content--- TERM";
    dos.write(presentationMessage.getBytes("UTF-8");
    dos.flush();

    // buffers
    byte[] readBuffer = new byte[4096];
    StringBuffer responseBuffer = new StringBuffer();

    // read data until command terminator string is found
    boolean readResponse = true;
    while (readResponse) {
        int dataBufferLength = dis.read(readBuffer);
        String chunk = new String(readBuffer, 0, dataBufferLength, "UTF-8"));
        responseBuffer.append(chunk);
        readResponse = ! chunk.endWith("--- TERM");
    }

    // Process data here
} else {
    // Notify missing connection here
}
// here i close the socket

當我執行這段代碼時,執行似乎就像一個魅力,直到第一次讀取超時。

使用第三台機器嗅探使用過的WIFI網絡即使代碼在讀取超時之前沒有拋出任何異常,我也看不到連接建立和寫入的流。

我在manifest中授予了android.permission.INTERNET

是否還有其他權限可以授予? 或者我做錯了什么?

在標准Java SE環境中執行相同的代碼一切順利。

我正在測試Nexus 5,Nexus 9和Samsung S3和S4上的代碼,該項目與API 14+兼容

編輯:修復了代碼示例中的拼寫錯誤

你正在閱讀dos和寫作dis。 你應該改變這一點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM