我在实现 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 应用程序的工作方式如下:
- 首先它创建 Socket 并将数据发送到其他设备并关闭 OutputStream。
- 第二部分是解析字节数组,然后使用相同的套接字返回响应。
任何想法如何更改我的功能,以便我可以在不阻塞的情况下读取输入流?
编辑:
所以问题出在IOS端,似乎Apple API需要关闭创建的套接字的两个流:读/写所以可以发送字节数组,这看起来很愚蠢,因为这样iphone应用程序无法接收并解析我的回复。