0

我使用 WCF 传输文件

在客户端 [WINFORM]

private void Send(TransferEntry Entry, int bufferSize)
    {
        using (FileStream fs = new FileStream(Entry.SrcPath, FileMode.Open, FileAccess.Read))
        {
            byte[] buffer = new byte[bufferSize];
            long sum = 0;
            int count = 0;
            using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, 0);
                listener.Bind(endpoint);
                listener.Listen(1);
                client.Receive(listener.LocalEndPoint, Entry.DestPath, Entry.Size, bufferSize);
                //i get an exception here.
                using (Socket socket = listener.Accept())
                {
                    do
                    {
                        count = fs.Read(buffer, 0, buffer.Length);
                        socket.Send(buffer, 0, count, SocketFlags.None);
                        sum += count;
                        worker.ReportProgress((int)((sum * 100) / Entry.Size));
                    } while (sum < Entry.Size);
                }
            }
        }
    }

在 WCF [服务]:在 IFileManager.cs 上:

[OperationContract]
    void Receive(System.Net.EndPoint endpoint, string destPath, long size, int bufferSize);

在 FileManagerService.cs 上:

public void Receive(EndPoint endpoint, string destPath, long size, int bufferSize)
    {
        using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
        {
            client.Connect(endpoint);
            using (FileStream fs = new FileStream(destPath, FileMode.Create, FileAccess.Write))
            {
                byte[] buffer = new byte[bufferSize];
                long sum = 0;
                int count = 0;
                do
                {
                    count = client.Receive(buffer, 0, buffer.Length, SocketFlags.None);
                    fs.Write(buffer, 0, count);
                } while (sum < size);
                fs.Flush();
            }
        }
    }

然后我在客户端 [Winform] 得到了这个异常

System.ServiceModel.CommunicationException was unhandled by user code Message=There was an error while trying to serialize parameter http://tempuri.org/:endpoint. The InnerException message was 'Type 'System.Net.IPEndPoint' with data contract name 'IPEndPoint:http://schemas.datacontract.org/2004/07/System.Net' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.'. Please see InnerException for more details.

为什么只有当我传递EndPoint参数时才会发生这种情况!我怎样才能让它工作?

4

1 回答 1

0

您的服务器期待一个EndPoint,但您正在发送一个IPEndPoint.

您可以通过告诉服务期望IPEndPoint使用ServiceKnownTypeAttribute来解决此问题。

于 2012-04-22T15:56:08.773 回答