类型'System.Net.Sockets.Socket'无法序列化

时间:2012-07-11 11:56:54

标签: c# asp.net wcf sockets

类型'System.Net.Sockets.Socket'无法序列化。请考虑使用DataContractAttribute属性对其进行标记,并使用DataMemberAttribute属性标记要序列化的所有成员。

我在WCF中创建一个服务,它打开连接并向服务器发送消息,但是当我运行服务时会给出错误。我不知道如何用数据契约属性标记它或如何解决问题。

public class Service1 : IService1
{


    public void Connect(String a , String b)
    {

        int hit = Convert.ToInt32(a);

        int delay = Convert.ToInt32(b);
        delay = delay * 1000; 

 // I have eliminated the log making part       string LogPath = "C:\\VoltTestApp\\Logs\\";


        for (int i = 1; i <= hit; i++)
        {

            try
            {
                TcpClient tcpClient = new TcpClient("10.111.13.72", 80);
                Console.WriteLine("Initialized Socket  .............\n");
                Socket socket = tcpClient.Client;
                string str = "ID_T$";

                try
                { // sends the text with timeout 10s
                    Console.WriteLine("Going To Send Request  .............\n");
                    Send(socket, Encoding.UTF8.GetBytes(str.Trim()), 0, str.Length, 10000);
               }


                socket.Close();
                tcpClient.Close();
                Console.WriteLine("Socket Closed  .............\n");
            }

            Thread.Sleep(delay);
        }

    }



    public  void Send(Socket socket, byte[] buffer, int offset, int size, int timeout)
    {
        try
        {
            int startTickCount = Environment.TickCount;
            int sent = 0;  // how many bytes is already sent
            do
            {
                if (Environment.TickCount > startTickCount + timeout)
                    throw new Exception("Timeout.");
                try
                {
                    sent += socket.Send(buffer, offset + sent, size - sent, SocketFlags.None);
                }
                catch (SocketException ex)
                {
                    if (ex.SocketErrorCode == SocketError.WouldBlock ||
                        ex.SocketErrorCode == SocketError.IOPending ||
                        ex.SocketErrorCode == SocketError.NoBufferSpaceAvailable)
                    {
                        // socket buffer is probably full, wait and try again
                        Thread.Sleep(30);
                    }
                    else
                        throw ex;  // any serious error occurr
                }
            } while (sent < size);
        }

    }

3 个答案:

答案 0 :(得分:1)

您无法明智地维护对wcf服务的调用之间的tcp连接。在你的情况下 我将从服务合同中删除Connect方法,在Service1类中将其更改为private, 从send方法中删除socket参数(在IService1及其在Service1类中的实现) 并从send方法调用connect方法(以便每次发送时连接和断开连接)

答案 1 :(得分:1)

在这种情况下,可能是因为您的服务上有一个公共方法,它以Socket作为参数。这很自然地,在尝试服务发现时无法正确序列化。

如果Send仅在内部使用,请将其设为私有。

答案 2 :(得分:0)

错误消息具有误导性,解决方法是不向DataContractAttribute添加System.Net.Sockets.Socket。问题是您无法通过网络发送套接字。更具体地说,您无法对其进行序列化,要发送它,您必须能够对其进行序列化。

您需要找到一个不涉及通过网络发送套接字(或将其保存到磁盘/数据库)的解决方案。

相关问题