user7653349
user7653349

Reputation: 11

C#.net Windows Service - how to log TCP port activities in a file?

How can I log port activities in C#.net WindowsService? Also, are there any issues with the following code? Socket programming is entirely new to me. I cant even log it.

    public void Start()
    {
        try
        {

            // Read server IPAddress and port details from the config
            string serverIP, serverPort;
            serverIP = ConfigurationManager.AppSettings["ServerIP"];
            serverPort = ConfigurationManager.AppSettings["ServerPort"];

            // Initialize server IPAddress and port number
            IPAddress serverIPAddress = IPAddress.Parse(serverIP);
            int serverPortNumber = int.Parse(serverPort);


            this.tcpListnr = new TcpListener(serverIPAddress, serverPortNumber);
            this.tcpListnr.Start();

            // Start listener thread
            this.tcpListnrThread = new Thread(this.ThreadProc);
            this.tcpListnrThread.Start();



        }
        catch (Exception ex)
        {
            if (Er != null)
                this.Er.LogError(ex,"Error in Start "); 
        }
    }

private void ThreadProc()
    {
        try
        {
            // Listen infinitly  
            while (true)
            {
                // Waiting for a connection 
                TcpClient tcpClient = this.tcpListnr.AcceptTcpClient();


                // Connected

                if (this.tcpListnrThread.IsAlive)
                {
                    try
                    {
                        Thread readDataThread = new Thread(this.ReadDataThreadProc);// Read data in a separate thread
                        readDataThread.Start(tcpClient);
                    }
                    catch(Exception ex)
                    {
                        this.Er.LogError(ex,"Thread Abort");
                    }
                }

            }
        }
        catch (Exception ex)
        {
            if (Er != null)
                this.Er.LogError(ex,"Error in ThreadProc - " );
        }

    }

Upvotes: 1

Views: 1475

Answers (1)

Sergio
Sergio

Reputation: 346

Here is the example. Note that there is no error checks, no check if there is more data in the stream and etc. But this could help you start.

// Bind ip and port
TcpListener listener = new TcpListener(new IPAddress(new byte[] { 127, 0, 0, 1 }), 12345);
// start listener
listener.Start();
// endless cycle
while (true)
{
    // acept client
    TcpClient client = listener.AcceptTcpClient();
    // using bgworker instead of thread, i like it more :D
    using (BackgroundWorker bw = new BackgroundWorker())
    {
        // sign for dowork
        bw.DoWork += Bw_DoWork;
        // run worker and passing TcpClient as argument
        bw.RunWorkerAsync(client);
    }
}

And the data process part

// this will execute every time in separate thread 
// when listener accept connection
private static void Bw_DoWork(object sender, DoWorkEventArgs e)
{
    TcpClient client = (TcpClient)e.Argument;
    // set read buffer length
    int inBuffLen = 1024;
    // declare input buffer
    byte[] inBuff = new byte[inBuffLen];

    // we will use network stream to read
    NetworkStream stream = client.GetStream();
    // real data length
    int rlen;
    // read from stream 1024 bytes of data and
    // in rlen we've got a REAL amount of data bytes
    rlen = stream.Read(inBuff, 0, inBuffLen);
    // declare data array
    byte[] data = new byte[rlen];
    // copy from source array to data array
    Array.Copy(inBuff, data, rlen);
    // now you can do with data whatever you want
    var s = "";
    for (int i = 0; i < data.Length; i++)
        s += string.Format("{0:X2}", data[i]);
    Debug.WriteLine(s);
}

Upvotes: 1

Related Questions