无法序列化类型“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);
}
}