为什么套接字不发送最后一条消息,除非它之前有延迟?

时间:2016-02-01 19:51:29

标签: java android sockets

好吧所以我正在看这段代码,它应该得到一个代表图像的字节数组,并将它一块一块地发送给服务器。当图像传输完成时,需要告知服务器,该结束消息是" CLOSE"。一切正常,但除非我取消注释Thread.sleep,否则不会发送结束消息。此外,由于某种原因,延迟需要非常大,例如100毫秒不起作用。如果有人能为这种行为提供解释,我将不胜感激,因为我对java没有很好的理解。

private class NetTask extends AsyncTask<Void, Void, Void>
{
    private String ip;
    private byte[] to_send;

    public NetTask(String ip, byte[] to_send)
    {
        this.ip = ip;
        this.to_send = to_send;
    }

    @Override
    protected Void doInBackground(Void...params)
    {
        try {
            Log.i(dTag, "" + to_send.length);
            Socket sck = new Socket(ip, 1234);
            DataOutputStream dOut = new DataOutputStream(sck.getOutputStream());
            dOut.write(ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(to_send.length).array());
            Log.d(dTag, "" + to_send.length);
            int x = 500;
            int len = to_send.length;
            for (int i = 0; i < len - x + 1; i += x)
                dOut.write(Arrays.copyOfRange(to_send, i, i + x));

            if (len % x != 0)
                dOut.write(Arrays.copyOfRange(to_send, len - len % x, len));
            /*try {
                Thread.sleep(1000);
            }
            catch (Exception ex) {
                Log.d(dTag, "thread sleep error");
            }*/
            dOut.write("CLOSE".getBytes());
            dOut.flush();
            dOut.close();
            sck.close();
        }
        catch (IOException ex) {
            Log.d(dTag, ex.getMessage());
        }
        return null;
    }
}

服务器在c#中,这是代码:

while (ok)
{
    sck.Listen(1000);
    Socket accepted = sck.Accept();
    buffer = new byte[accepted.SendBufferSize];
    int bytesRead = -1;
    bool reading = true;
    int im_size = -1;
    int index = 0;
    byte[] image = null;
    while (reading)
    {
        bytesRead = accepted.Receive(buffer);
        if (bytesRead == 5)
            Console.WriteLine(bytesRead);
        string strData = "YADA";
        byte[] formatted = new byte[bytesRead];
        if (bytesRead == 5)
        {
            for (int i = 0; i < bytesRead; i++)
            {
                formatted[i] = buffer[i];
            }
            strData = Encoding.ASCII.GetString(formatted);
        }
        if (strData == "CLOSE")
        {
            Console.WriteLine("GOT CLOSE MESSAGE");
            Image im = Image.FromStream(new MemoryStream(image));
            im.Save(@"D:\im1.bmp");
        }
        else
        {
            if (im_size == -1)
            {
                im_size = BitConverter.ToInt32(buffer, 0);
                image = new byte[im_size];
                Console.WriteLine(im_size);
            }
            else
            {
                for (int i = 0; i < bytesRead && index < im_size; i++)
                {
                    image[index++] = buffer[i];
                }
            }
        }
    }
    accepted.Close();
}

0 个答案:

没有答案