8

我正在开发一个 java 客户端来使用下面的 WCF 服务。由于 WCF 服务使用的是 Stream 技术,我也希望在 java 客户端代码中使用 Stream 技术来减少内存使用。有没有人可以给我一个关于如何写它的建议?谢谢。

namespace TmpWcfStream
{
    [MessageContract]
    public class InputMessage
    {
        [MessageHeader(MustUnderstand = true)]
        public string TranName { get; set; }

        [MessageBodyMember(Order=1)]
        public Stream FileData { get; set; }
    }

    [MessageContract]
    public class OutputMessage
    {
        [MessageBodyMember(Order = 100)]
        public bool Success { get; set; }

        [MessageBodyMember(Order = 200)]
        public string ErrorMsg  { get; set; }
    }
}

namespace TmpWcfStream
{
    public class UploadDataSvc : UploadSvcContract
    {
        private const int bufferLen = 4096;

        public OutputMessage UploadData(InputMessage msg)
        {
            OutputMessage outputMsg = new OutputMessage { ErrorMsg = string.Empty, Success = true };

            try
            {
                Stream inputStream = msg.FileData;
                String filePath = @"C:\tmp\output.txt";

                using (FileStream targetStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    byte[] buffer = new byte[bufferLen];
                    int count = 0;
                    while ((count = inputStream.Read(buffer, 0, bufferLen)) > 0)
                    {
                        targetStream.Write(buffer, 0, count);
                    }
                }
                inputStream.Close();
            }
            catch(Exception e)
            {
                outputMsg.Success = false;
                outputMsg.ErrorMsg = e.ToString();
            }

            return outputMsg;
        }
}
4

0 回答 0