Здравствуйте!
Есть windows служба. Ранее при старте она запускала поток, который общался посредством сокетов (был клиентом) с внешним приложением в сети. При этом все работало хорошо. Теперь нужно, чтобы служба общалась посредством сокетов (только уже как сервер) с консольными приложением (клиентом) на этом же компьютере, что и сама служба. Но как только клиент пытается отправить данные службе, служба останавливается (при этом в журнале никаких сообщений об ошибках нет), а клиент выдает исключение, что соединение было разорвано. Помогите, пожалуйста, разобраться.
Сервер (служба)
| Код | byte[] bytes = new Byte[2048]; List<byte> d; Socket listener = null, handler = null;
Functions.WriteTrace("UIClientServer started"); do { // Establish the local endpoint for the socket. IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11000);
// Create a TCP/IP socket. listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and // listen for incoming connections. try { listener.Bind(localEndPoint); listener.Listen(10); Functions.WriteTrace("Waiting for a connection...");
// Start listening for connections. while (true) { data = null; // Program is suspended while waiting for an incoming connection. handler = listener.Accept(); //после этой строчки служба останавливается
if (handler.Connected && handler.Poll(-1, SelectMode.SelectRead)) { ...прием данных }
if (handler.Connected && bytes.Length > 0 && bytes[0] == 0xAE) { ...обработка полученных данных d = new List<byte>(0xAE); d.AddRange(Serialize(signal));
if (handler.Connected && handler.Poll(-1, SelectMode.SelectWrite)) { handler.Send(d.ToArray()); } }
handler.Shutdown(SocketShutdown.Both); handler.Close(); Thread.Sleep(2000); }//while
} catch (Exception ex) { Functions.WriteTrace(((SocketException)ex).ErrorCode.ToString(), TraceEventType.Error); Functions.WriteTrace(ex.ToString(), TraceEventType.Error);
handler.Shutdown(SocketShutdown.Both); handler.Close(); Functions.WriteTrace("timeout 2 min", TraceEventType.Warning); Thread.Sleep(120000); } } while (DriversService.iAmAlive);
|
Консольное приложение (клиент)
| Код | byte[] bytes = new byte[2048]; // Data buffer for incoming data. List<byte> d; Socket sender = null;
bool commandSent = false; // Connect to a remote device. do { try { // Establish the remote endpoint for the socket. IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11000);
// Create a TCP/IP socket. sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Connect the socket to the remote endpoint. Catch any errors. sender.Connect(remoteEP);
while (true) { if (sender.Connected && controller.CommandReady && !commandSent) { ...готовим данные для отправка
if (sender.Poll(-1, SelectMode.SelectWrite)) { // Send the data through the socket. int bytesSent = sender.Send(data.ToArray()); //здесь вываливается исключение commandSent = true; }
}
if (sender.Connected && commandSent && sender.Poll(-1, SelectMode.SelectRead)) { // Receive the response from the remote device. int bytesRec = sender.Receive(bytes);
if (bytes[0] == 0xAE) { ...обработка полученных данных }
} Thread.Sleep(2000); } } catch (Exception ex) { Console.WriteLine(ex.ToString() + '\n' + ((SocketException)ex).ErrorCode.ToString());
Console.WriteLine(" timeout 2 minutes"); Thread.Sleep(120000); } } while (iAmAlive);
|
|