【发布时间】:2012-07-11 11:56:54
【问题描述】:
类型“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);
}
}
【问题讨论】:
-
如果没有相关代码,我们无法为您提供帮助。但建议不要尝试将实际的套接字作为消息发送。
-
提供一些代码。不要认为序列化 Socket 在这里是正确的..
-
因此,如果我消除发送功能并简单地在连接功能中执行该部分,以便我的方法不采用套接字参数,它会工作吗?或者什么是可能的解决方案,因为它是我的第一个 wcf 应用程序
-
进一步查看我的答案 - 如果您不在其他任何地方使用发送,请将其设为私有。 =)