Android从输入流中检索字节

时间:2012-11-13 11:22:11

标签: c# java android sockets inputstream

我正在尝试检索由c#中编程的服务器传输的字节,如下所示:

static void Main(String[] args){
    Socket sListen = new Socket(AddressFamily.InterNetwork, SocketType.Stream,     ProtocolType.Tcp);
    IPAddress IP = IPAddress.Parse("10.0.0.92");
    IPEndPoint IPE = new IPEndPoint(IP, 4321);
    sListen.Bind(IPE);
    Console.WriteLine("Service is listening ...");
    sListen.Listen(2);
    while (true){
        Socket clientSocket;
        try{
            clientSocket = sListen.Accept();
        }
        catch{
            throw;
        }
        byte[] buffer = ReadImageFile("path to image");
        clientSocket.Send(buffer, buffer.Length, SocketFlags.None);
        Console.WriteLine("Send success!");
    }
}

private static byte[] ReadImageFile(String img){
    FileInfo fileinfo = new FileInfo(img);
    byte[] buf = new byte[fileinfo.Length];
    FileStream fs = new FileStream(img, FileMode.Open, FileAccess.Read);
    fs.Read(buf, 0, buf.Length);
    fs.Close();
    //fileInfo.Delete ();
    GC.ReRegisterForFinalize(fileinfo);
    GC.ReRegisterForFinalize(fs);
    return buf;
}

当我在c#中编写客户端并在pc中运行它时,上面的代码工作正常。但是我想检索Android设备中服务器传输的字节。

android连接到服务器成功,但它不会完成它的工作,基本上它不会传递'波纹管代码中的'while循环'。我认为字节长度有问题,因为它永远不会达到'-1'。

Android java代码(客户端):

Socket socket = new Socket("ip", 4321);
InputStream is = socket.getInputStream();
byte[] buffer = new byte[1024];
int read = is.read(buffer);
while(read != -1){
    read = is.read(buffer);
}

is.close();
socket.close();

我提前感谢任何帮助, 谢谢,

2 个答案:

答案 0 :(得分:0)

我不明白你的Java代码。您正在使用的read(byte[])方法一次又一次地在缓冲区中写入1024字节(或更少)。您正在覆盖以前的缓冲区内容。您可能希望将下载的数据写入某个地方,例如OutputStream。例如:

    Socket socket = new Socket("ip", 4321);
    InputStream is = socket.getInputStream();
    OutputStream os = ...; // Where to save data, for example, new ByteArrayOutputStream();

    copyStreams(is, os);

    is.close();
    socket.close();


    public static void copyStreams(InputStream is, OutputStream os) throws IOException {
        byte[] buffer = new byte[1024];
        int numBytesRead;

        for (;;) {
            bytesRead = is.read(buffer);
            if (bytesRead <= 0)
                break;
            os.write(buffer, 0, bytesRead);
        }
    }

答案 1 :(得分:0)

在服务器关闭连接之前,客户端read()方法永远不会返回-1。你没有这样做,所以它永远不会发生。