我在Android和IOS之间实现套接字连接时遇到了一点问题。当我使用我的应用程序连接两个 Android 运行设备时,一切正常。但是当我必须从 Iphone 应用程序接收一些数据时,我的 readStream 函数被阻塞,我可以在另一部分关闭套接字后接收所有数据,这样我就无法向它返回任何响应。这是我用来收听的内容:
try {
serverSocket = new ServerSocket(5000);
Log.d("","CREATE SERVER SOCKET");
} catch (IOException e) {
e.printStackTrace();
}
while(state){
try {
if(serverSocket!=null){
client = serverSocket.accept();
client.setKeepAlive(true);
client.setSoTimeout(10000);
// LOGS
Log.w("READ","is connected : "+client.isConnected());
Log.w("READ","port : "+client.getPort());
Log.w("READ","ipadress : "+client.getInetAddress().toString());
InputStream is = client.getInputStream();
Log.w("READ","is Size : "+is.available());
byte[] bytes = DNSUtils.readBytes(is);
Log.v("","-------------------------");
for(int i=0;i<bytes.length;i++){
Log.w("READ","bytes["+i+"] : "+bytes[i]);
}
Log.v("","-------------------------");
try {
Log.w("READ","packetType : "+bytes[4]);
if(bytes!=null)
DNSUtils.getPacketType(bytes[4], bytes, client);
} catch(Exception e){
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
Log.v("","IOException");
ResponseERR pack = new ResponseERR();
ResponseERR.errorMsg = "Socket TimeOut exception!";
byte[] packet = pack.createNewPacket();
try {
if(client!=null){
OutputStream out = client.getOutputStream();
out.write(packet);
out.flush();
client.shutdownOutput();
client.close();
Log.e("READDATAFROMSOCKET","ResponseERR Send.");
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
这是我用来将 InputStream
转换为 Byte Array
的函数:
public static byte[] readBytes(InputStream inputStream) throws IOException {
// this dynamically extends to take the bytes you read
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
// this is storage overwritten on each iteration with bytes
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
// we need to know how may bytes were read to write them to the byteBuffer
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
// and then we can return your byte array.
return byteBuffer.toByteArray();
}
Iphone/Android 应用程序都是这样工作的:
- 首先它创建套接字并将数据发送到其他设备并关闭 OutputStream。
- 第二部分是解析字节数组,然后使用相同的套接字返回响应。
有什么想法可以更改我的函数以便我可以无阻塞地读取输入流吗?
编辑:
So the problem was on IOS side, it seems that Apple API require to close both streams of the created socket : read/write so the byte array can be send, which seems really stupid, because in that way the iphone app can't receive and parse my response.
最佳答案
与您编辑中的评论相反,这是您的错,而不是 Apple 的错。您需要重新设计您的 API。您的 readBytes()
方法读取流直到结束,这仅在对等方关闭连接时发生。如果您只想读取一些 字节,read(byte[])
已经这样做了,并告诉您有多少,而不需要结束流。我会把这个方法扔掉。
关于Java套接字读取输入流而不阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12053423/