Android 如何在tcp套接字中从对象读取数据
我正在使用TCP套接字连接。 服务器发送一个对象中的数据,我需要接收和读取它。 服务器像这样发送数据Android 如何在tcp套接字中从对象读取数据,android,Android,我正在使用TCP套接字连接。 服务器发送一个对象中的数据,我需要接收和读取它。 服务器像这样发送数据 public class SymbolData { public string Symbol { get; set; } public double AskPrice { get; set; } public double BidPrice { get; set; } public double Open { get; set; } public double High { get; set;
public class SymbolData
{
public string Symbol { get; set; }
public double AskPrice { get; set; }
public double BidPrice { get; set; }
public double Open { get; set; }
public double High { get; set; }
public double Low { get; set; }
public double Close { get; set; }
public double PerChange { get; set; }
public double NetChange { get; set; }
public int Volume { get; set; }
}
我的代码如下。我不知道我的流程是否正确
public class Client implements Runnable, java.io.Serializable{
@Override
public void run() {
// TODO Auto-generated method stub
try {
Socket s = new Socket("172.16.x.xx",xxx);
//outgoing stream redirect to socket
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
InputStream is = new DataInputStream(s.getInputStream());
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[1024];
while ((nRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
try {
deserialize(data);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
buffer.flush();
InputStreamReader(s.getInputStream()));
s.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//反序列化字节
public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
ByteArrayInputStream b = new ByteArrayInputStream(bytes);
ObjectInputStream o = new ObjectInputStream(b);
return o.readObject();
}
请帮助Catch NPE/使函数也抛出NPE,以防您没有读到任何我尝试过的内容,但仍然关闭了应用程序。我可以看到类似O4的数据��'�?我�Q���?���T��?��4] K_�?��c] b��?Y�9y,��?我�8l�L�?-�~kH�?��) 如何将此数据转换为可读格式设置ObjectInputStream附近的java.io.StreamCorruptedException o=新ObjectInputStream(b);