如何从tcp socket android中的对象读取数据

时间:2013-06-27 06:09:22

标签: 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 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();
}

请帮忙

0 个答案:

没有答案