简体   繁体   English

Android套接字已连接但不发送数据

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

I'm developing an Android client app which talks to server via a plain TCP Socket, let's assume that the server ip 192.168.1.2 and the androdi device ip is 192.168.1.3. 我正在开发一个Android客户端应用程序,通过普通的TCP Socket与服务器通信,我们假设服务器IP 192.168.1.2和androdi设备IP是192.168.1.3。

I open the socket, i check if socket is connected (i get true as result) and after that i write a presentation message. 我打开套接字,我检查套接字是否已连接(我的结果是真的)然后我写了一个演示文稿消息。

Here is my code 这是我的代码

// 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

When i execute this code the execution seems working like a charme until the first read which timesout. 当我执行这段代码时,执行似乎就像一个魅力,直到第一次读取超时。

Sniffing the used WIFI network with a third machine i can't see the connection establishment and the written stream even if the code doesn't throw any exception before the read timeout. 使用第三台机器嗅探使用过的WIFI网络即使代码在读取超时之前没有抛出任何异常,我也看不到连接建立和写入的流。

I granted the android.permission.INTERNET in manifest. 我在manifest中授予了android.permission.INTERNET

Are there some other permissions to grant? 是否还有其他权限可以授予? or what i'm doing wrong? 或者我做错了什么?

Executing the same code in a standard Java SE environment everything goes fine. 在标准Java SE环境中执行相同的代码一切顺利。

I'm testing the code on a Nexus 5, Nexus 9 and Samsung S3 and S4 and the project is compatible with API 14+ 我正在测试Nexus 5,Nexus 9和Samsung S3和S4上的代码,该项目与API 14+兼容

Edit: Fixed typo in code example 编辑:修复了代码示例中的拼写错误

You are reading from dos and writing to dis. 你正在阅读dos和写作dis。 You should reverse that. 你应该改变这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM