Tcpip Listner Problem c# receiving data in shape of three message from device how to combine three message into one or ignor second or third Message and save in to text File

SAQ 21 Reputation points
2022-08-18T15:09:47.79+00:00

Hi, I am new to programming and creating TCPIP Listner in C# my Tcpip Listner (server ) is attached with the device. When trying to send data from the device. Devise Send Three string

232536-capture.png

I want to receive string 1 only not string 2 or 3 String. Kindly advise us on how to ignore string 2 or string 3 when the device sends data to TCPip Listener . or

is it possible to combine string 1 + string + and string 3 in one string and save it to a text file.,

any hint or advice appreciatable.

below is my code C#

using System;  
using System.Collections.Generic;  
using System.ComponentModel;  
using System.Data;  
using System.Drawing;  
using System.Linq;  
using System.Text;  
using System.Windows.Forms;  
using System.Net;  
using System.Net.Sockets;  
using System.IO;  
using System.Data.OleDb;  
using System.Configuration;  
using static System.Windows.Forms.VisualStyles.VisualStyleElement;  
  
namespace TCPServer01  
{  
    public partial class Form1 : Form  
    {  
  
          
        TcpListener mTCPListener;  
        TcpClient mTCPClient;  
        byte[] mRx;  
        string mydata;  
          
  
        private List<ClientNode> mlClientSocks;  
        private object connection;  
  
        public Form1()  
        {  
              
            InitializeComponent();  
            mlClientSocks = new List<ClientNode>(2);  
            CheckForIllegalCrossThreadCalls = false;  
              
        }  
  
        IPAddress findMyIPV4Address()  
        {  
            string strThisHostName = string.Empty;  
            IPHostEntry thisHostDNSEntry = null;  
            IPAddress[] allIPsOfThisHost = null;  
            IPAddress ipv4Ret = null;  
  
            try  
            {  
                strThisHostName = System.Net.Dns.GetHostName();  
                thisHostDNSEntry = System.Net.Dns.GetHostEntry(strThisHostName);  
                allIPsOfThisHost = thisHostDNSEntry.AddressList;  
  
                for (int idx = allIPsOfThisHost.Length - 1; idx >= 0; idx--)  
                {  
                    if (allIPsOfThisHost[idx].AddressFamily == AddressFamily.InterNetwork)  
                    {  
                        ipv4Ret = allIPsOfThisHost[idx];  
                        break;  
                    }  
                }  
            }  
            catch (Exception exc)  
            {  
                MessageBox.Show(exc.Message);  
            }  
  
            return ipv4Ret;  
        }  
  
        private void btnStartListening_Click(object sender, EventArgs e)  
        {  
            IPAddress ipaddr;  
            int nPort;  
  
            if (!int.TryParse(tbPort.Text, out nPort))  
            {  
                nPort = 23000;  
            }  
            if (!IPAddress.TryParse(tbIPAddress.Text, out ipaddr))  
            {  
                MessageBox.Show("Invalid IP address supplied.");  
                return;  
            }  
              
            mTCPListener = new TcpListener(ipaddr, nPort);  
  
            mTCPListener.Start();  
            lblServerStatus.Text = "Server Started ";  
             
  
            mTCPListener.BeginAcceptTcpClient(onCompleteAcceptTcpClient, mTCPListener);  
             
  
        }  
  
        void onCompleteAcceptTcpClient(IAsyncResult iar)  
        {  
            TcpListener tcpl = (TcpListener)iar.AsyncState;  
            TcpClient tclient = null;  
            ClientNode cNode = null;  
  
            try  
            {  
                tclient = tcpl.EndAcceptTcpClient(iar);  
  
                printLine("Client Connected...");  
  
                tcpl.BeginAcceptTcpClient(onCompleteAcceptTcpClient, tcpl);  
  
                lock (mlClientSocks)  
                {  
                    mlClientSocks.Add((cNode = new ClientNode(tclient, new byte[1024], new byte[1024], tclient.Client.RemoteEndPoint.ToString())));  
                    lbClients.Items.Add(cNode.ToString());                      
                }  
  
                tclient.GetStream().BeginRead(cNode.Rx, 0, cNode.Rx.Length, onCompleteReadFromTCPClientStream, tclient);  
  
                //mRx = new byte[1024];  
                //mTCPClient.GetStream().BeginRead(mRx, 0, mRx.Length, onCompleteReadFromTCPClientStream, mTCPClient);  
  
  
            }  
            catch (Exception exc)  
            {  
                MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);  
            }  
        }  
  
        void onCompleteReadFromTCPClientStream(IAsyncResult iar)  
        {  
            TcpClient tcpc;  
            int nCountReadBytes = 0;  
            string strRecv;  
            ClientNode cn = null;  
  
            try  
            {  
                lock(mlClientSocks)  
                {  
                    tcpc = (TcpClient)iar.AsyncState;  
  
                    cn = mlClientSocks.Find(x => x.strId == tcpc.Client.RemoteEndPoint.ToString());  
  
                    nCountReadBytes = tcpc.GetStream().EndRead(iar);  
  
                    if (nCountReadBytes == 0)// this happens when the client is disconnected  
                    {  
                        MessageBox.Show("Client disconnected.");  
                        mlClientSocks.Remove(cn);  
                        lbClients.Items.Remove(cn.ToString());  
                        return;  
                    }  
  
                    strRecv = Encoding.ASCII.GetString(cn.Rx, 0, nCountReadBytes).Trim();  
                    //strRecv = Encoding.ASCII.GetString(mRx, 0, nCountReadBytes);  
  
                    printLine(DateTime.Now + " - " + cn.ToString() + ": " + strRecv);  
  
                      
  
                    cn.Rx = new byte[1024];  
  
                    tcpc.GetStream().BeginRead(cn.Rx, 0, cn.Rx.Length, onCompleteReadFromTCPClientStream, tcpc);  
                    // Store Data in Text File   
  
                    TextWriter txt = new StreamWriter("C:\\Users\\SAQ\\Desktop\\demo.txt", append:true);  
                    txt.Write("\n" + strRecv );  
                    txt.Close();  
  
                                        
  
                    // Database Connection  
                   OleDbConnection connection = new OleDbConnection();  
                   connection.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source= C:\mydat.accdb";  
                    
                    var datain = strRecv;  
                    datain = datain.Replace("*", "0");  
                    datain =   datain.Substring(0, 174);  
                    //string result = str.Substring(0, 170);  
  
                   
  
  
                    //  Database Connection   
  
                     OleDbCommand cmd1 = new OleDbCommand();  
                     connection.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source= C:\mydat.accdb";  
                     mydata = strRecv.Replace("\n", "");  
  
  
                     connection.Open();  
  
                     cmd1.Connection = connection;  
                     cmd1.CommandText = "insert into tbl_Message(Message) values ('" + mydata + "' )";  
                     cmd1.ExecuteNonQuery();  
                     connection.Close();  
  
                      
                                         
                }  
  
  
            }  
            catch (Exception ex)  
            {  
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);  
  
                lock (mlClientSocks)  
                {  
                    printLine("Client disconnected: " + cn.ToString());  
                    mlClientSocks.Remove(cn);  
                    lbClients.Items.Remove(cn.ToString());  
                }  
  
            }  
        }  
  
          
  
        public void printLine(string _strPrint)  
        {  
            tbConsoleOutput.Invoke(new Action<string>(doInvoke), _strPrint);  
        }  
  
        public void doInvoke(string _strPrint)  
        {  
            tbConsoleOutput.Text = _strPrint + Environment.NewLine + tbConsoleOutput.Text;  
        }  
  
        private void btnSend_Click(object sender, EventArgs e)  
        {  
            if (lbClients.Items.Count <= 0) return;  
            if (string.IsNullOrEmpty(tbPayload.Text)) return;  
  
            ClientNode cn = null;  
  
            lock(mlClientSocks)  
            {  
                cn = mlClientSocks.Find(x => x.strId == lbClients.SelectedItem.ToString());  
                cn.Tx = new byte[512];  
  
                try  
                {  
                    if (cn != null)  
                    {  
                        if (cn.tclient!= null)  
                        {  
                            if (cn.tclient.Client.Connected)  
                            {  
                                cn.Tx = Encoding.ASCII.GetBytes(tbPayload.Text);  
                                cn.tclient.GetStream().BeginWrite(cn.Tx, 0, cn.Tx.Length, onCompleteWriteToClientStream, cn.tclient);  
                            }  
                        }  
                    }  
                }  
                catch (Exception exc)  
                {  
                    MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);  
                }  
            }  
        }  
  
        private void onCompleteWriteToClientStream(IAsyncResult iar)  
        {  
            try  
            {  
                TcpClient tcpc = (TcpClient)iar.AsyncState;  
                tcpc.GetStream().EndWrite(iar);  
            }  
            catch (Exception exc)  
            {  
                MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);  
            }  
        }  
  
        private void btnFindIPv4IP_Click(object sender, EventArgs e)  
        {  
            IPAddress ipa = null;  
            ipa = findMyIPV4Address();  
  
            if (ipa != null)  
            {  
                tbIPAddress.Text = ipa.ToString();  
            }  
        }  
  
        private void btnFindIPv4IP_Click_1(object sender, EventArgs e)  
        {  
            IPAddress ipa = null;  
  
            ipa = findMyIPV4Address();  
            if (ipa != null)  
            {  
                tbIPAddress.Text = ipa.ToString();  
            }  
        }  
  
             
          
  
        private void btnServerStop_Click(object sender, EventArgs e)  
        {  
            mTCPListener.Start();  
  
            lblServerStatus.Text = "Server Stop ";  
        }  
    }  
}  
  
Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,827 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,233 questions
{count} votes