【发布时间】:2015-02-20 21:01:57
【问题描述】:
我正在开发一个通过普通 TCP Socket 与服务器通信的 Android 客户端应用程序,假设服务器 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 网络,即使代码在读取超时之前没有抛出任何异常,我也看不到连接建立和写入的流。
我在清单中授予了 android.permission.INTERNET。
还有其他要授予的权限吗?还是我做错了什么?
在标准 Java SE 环境中执行相同的代码一切正常。
我正在 Nexus 5、Nexus 9 和三星 S3 和 S4 上测试代码,该项目与 API 14+ 兼容
编辑:修正了代码示例中的错字
【问题讨论】:
-
您只是在讲述您的客户。但是也有服务器。请说出您在服务器端看到的内容。
-
服务器端我不会从客户端传入流量。我无法理解的事情是为什么 JSE 环境中的相同代码可以正常工作,而在移动环境中我会以这种方式被踩到
-
但是你看到客户端连接了吗?
-
广告写的套接字告诉我已连接位嗅探网络我没有从客户端和服务器进行任何通信