请看下面的代码,它在我的Windows服务中不是很稳定,启动一段时间后,它会抛出错误:
例外情况如下,请帮忙吗?应用: REMSServerService.exe框架版本:v4.0.30319描述: 未知异常.Info:System.Net.Sockets.SocketException Stack in System.Net.Sockets.Socket.AcceptCallback(System.Object)in System.Net.Sockets.Socket.RegisteredWaitCallback(System.Object的, 布尔)在 System.Threading._ThreadPoolWaitOrTimerCallback.PerformWaitOrTimerCallback(SYSTE m.Object, 布尔值)
发现错误: readsize = listensocket2.Receive(buffer_receive);
该项目位于数据通信中心,客户端是GPRS DTU套接字客户端。
请帮助!!!
第一部分:
protected override void OnStart(string[] args)
{
IPEndPoint endpoint = new IPEndPoint(RemsSocket.myip, RemsSocket.webport);
Socket listensocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listensocket.Bind(endpoint);
listensocket.Listen(200);
Thread th = new Thread(new ParameterizedThreadStart(RemsSocket.listen_send));
th.IsBackground = true;
th.Start(listensocket);
}
第二部分:
public static void listen_send(object source)
{
while (true)
{
done.Reset();
Socket listensocket = (Socket)source;
listensocket.BeginAccept(new AsyncCallback(acceptcallback_send), listensocket);
done.WaitOne();
}
}
public static void acceptcallback_send(IAsyncResult ar)
{
done.Set();
Socket socket = (Socket)ar.AsyncState;
Socket listensocket2 = socket.EndAccept(ar);
byte[] buffer_validate = new byte[buffersize];
string hostcode = "";
byte[] buffer_send = Hex.HexStringToByteArray(validate_code);
listensocket2.Send(buffer_send, 0, buffer_send.Length, SocketFlags.None);
listensocket2.Receive(buffer_validate);
int readsize = buffer_validate.Length; //listensocket2.EndReceive(ar);
if (readsize > 0)
{
bool success = FirstValidate(buffer_validate, ref hostcode);
bool validate = BLL.ExtHostBLL.CanCommunicate(hostcode);
if (success && validate)
{
LoopSendReceive(hostcode, listensocket2);
}
}
}
第三部分:
public static void LoopSendReceive(string hostcode, Socket listensocket2)
{
listensocket2.Blocking = true;
byte[] buffer_receive = new byte[buffersize];
bool validate = BLL.ExtHostBLL.CanCommunicate(hostcode);
while (validate)
{
Thread.Sleep(500);
int readsize;
bool success;
IPEndPoint clientipe = (IPEndPoint)listensocket2.RemoteEndPoint;
byte commandByte = Hex.HexStringToByteArray(command_8);
listensocket2.Send(commandByte, 0, commandByte.Length, SocketFlags.None);
listensocket2.ReceiveTimeout = 5000;
int countSocketException = 0;
readsize = listensocket2.Receive(buffer_receive);
if (readsize != 0)
{
clientipe = (IPEndPoint)listensocket2.RemoteEndPoint;
ClientDto client = hostList.FirstOrDefault(c => c.Ip == clientipe.Address.ToString());
ParseChannel.AlertStatus[] data;
ParseChannel channel = new ParseChannel();
success = channel.Parse(buffer_receive, client, out data);
if (!success)
{
continue;
}
SaveData(data, client);
}
}
}