using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.ServiceProcess;
namespace WindowsService1
partial class TestService : ServiceBase
protected override void OnStart(string[] args)
TcpListenerSample.isEnabled = true;
workerThread = new Thread(new ThreadStart(TcpListenerSample.Listen));
using (EventLog eventLog = new EventLog("Application"))
eventLog.Source = "Application";
eventLog.WriteEntry("ex", EventLogEntryType.Information, 101, 1);
protected override void OnStop()
TcpListenerSample.isEnabled = false;
using System.Net.Sockets;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
public class TcpListenerSample
public static volatile bool isEnabled;
public static void Listen()
TcpListener server = new TcpListener(IPAddress.Any, port);
while (true && isEnabled)
TcpClient client = server.AcceptTcpClient();
NetworkStream inputStream = client.GetStream();
while (!inputStream.DataAvailable) ;
bytes = new byte[client.Available];
i = inputStream.Read(bytes, 0, bytes.Length);
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
MatrixValidationRequest matrixValidation = Deserialize<MatrixValidationRequest>(data);
byte[] msg = System.Text.Encoding.ASCII.GetBytes(matrixValidation.SourceName.ToUpper());
if(IsSocketConnected(client.Client))
inputStream.Write(msg, 0, msg.Length);
public static T Deserialize<T>(string input) where T : class
System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(T));
using (StringReader sr = new StringReader(input))
return (T)ser.Deserialize(sr);
private static bool IsSocketConnected(Socket socket)
return !(socket.Poll(1, SelectMode.SelectRead) && socket.Available == 0);
catch (SocketException) { return false; }