problem in Sending data from client to server

ayna

New member
Joined
Aug 9, 2014
Messages
1
Programming Experience
Beginner
In my client-server c# app i need to send some data(i.e.string) from client to server but it's not working for no reason.
Can anyone plz find the error in SendData method?
Client code:

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;


namespace tcp_client
{
    public partial class Form1 : Form
    {
        System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
        NetworkStream serverStream;
        public Form1()
        {
            InitializeComponent();
        }


        private void Form1_Load(object sender, EventArgs e)
        {


        }
        public void ConnectToServer()
        {
            string server_localip = GetLocalIP();
            clientSocket.Connect(server_localip, 8888);


        }


        public void SendData(string dataTosend)
        {
            if (string.IsNullOrEmpty(dataTosend))
                return;
            NetworkStream serverStream = clientSocket.GetStream();
            byte[] outStream = System.Text.Encoding.ASCII.GetBytes(dataTosend);
            serverStream.Write(outStream, 0, outStream.Length);
            serverStream.Flush();
          
            
        }


server code:

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.Diagnostics;
namespace tcp_server
{
    public partial class Form1 : Form
    {
        public int cpuLoad;
        private PerformanceCounter cpuCounter;
      static  public string curIP;
       public static string get_localip = GetLocalIP();
        
        public Form1()
        {
            InitializeComponent();
            InitialiseCPUCounter();
            timer1.Start();
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            lblServerIP.Text += " "+get_localip;
        }
          private static TcpListener _listener;
        
           public  void StartServer() 
    {
         System.Net.IPAddress localIPAddress = System.Net.IPAddress.Parse(get_localip);
        IPEndPoint ipLocal = new IPEndPoint(localIPAddress, 8888);
        _listener = new TcpListener(ipLocal);
        _listener.Start();
        WaitForClientConnect();
     
    }
    private  void WaitForClientConnect()
    {
        object obj = new object();
        _listener.BeginAcceptTcpClient(new System.AsyncCallback(OnClientConnect), obj);
    }
    public void OnClientConnect(IAsyncResult asyn)
    {
        try
        {
          
            TcpClient clientSocket = default(TcpClient);
           // Socket sck;
        
            
            clientSocket = _listener.EndAcceptTcpClient(asyn);
         IPAddress add= IPAddress.Parse(((IPEndPoint)clientSocket.Client.RemoteEndPoint).Address.ToString());
         curIP = add.ToString();
         //Form1 myform = new Form1();
         //myform.lstIP.Items.Add(curIP);
         this.Invoke(new Action(() =>
         {
             lstIP.Items.Add("client connected with ip" + curIP);
             //MessageBox.Show("cleint connected with ip:" + curIP);
         }));
        // MessageBox.Show("cleint connected with ip:"+ curIP);
         
            HandleClientRequest clientReq = new HandleClientRequest(clientSocket);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }


        WaitForClientConnect();
    }


    public void btnStart_Click(object sender, EventArgs e)
    {
        
        StartServer();
        btnStart.Text = "Listening";
        btnStart.Enabled = false;
        
       


    }
    private void InitialiseCPUCounter()
    {
        cpuCounter = new PerformanceCounter(
        "Processor",
        "% Processor Time",
        "_Total",
        true
        );
    }


    private void timer1_Tick(object sender, EventArgs e)
    {
        cpuLoad = Convert.ToInt32(cpuCounter.NextValue());
        this.txtCPUusage.Text =
 cpuLoad.ToString() +
 "%";
    }
  static  public string GetLocalIP()
    {
        IPHostEntry host;
        host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (IPAddress ip in host.AddressList)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {
                return ip.ToString();
            }
        }
        return "127.0.0.1";
    }
}
    }


HandleClientRequest.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Data;
using System.Data.SqlClient;


namespace tcp_server
{
    class HandleClientRequest
    {
        TcpClient _clientSocket;
        NetworkStream _networkStream = null;
        string []arr;
        public HandleClientRequest(TcpClient clientConnected)
        {
            this._clientSocket = clientConnected;
            


        }
        public void StartClient()
        {
            _networkStream = _clientSocket.GetStream();
            WaitForRequest();
        }


        public void WaitForRequest()
        {
            byte[] buffer = new byte[_clientSocket.ReceiveBufferSize];


            _networkStream.BeginRead(buffer, 0, buffer.Length, ReadCallback, buffer);
        }




        private void ReadCallback(IAsyncResult result)
        {
            NetworkStream networkStream = _clientSocket.GetStream();
            try
            {
                int read = networkStream.EndRead(result);
                if (read == 0)
                {
                    _networkStream.Close();
                    _clientSocket.Close();
                    return;
                }


                byte[] buffer = result.AsyncState as byte[];
                string data = Encoding.Default.GetString(buffer, 0, read);
                arr=data.Split(new char[]{';'},2);
                string impi = arr[0];
                string impu = arr[1];
                //Form1 f1 = new Form1();
                //f1.txtCIP.Text = "IMPI:" + arr[0] + "\tIMPU:" + arr[1] + "\n";
         
                int newCritical_No=0;


                
                //do the job with the data here
                //................job.....................//
                string conString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Ayne\Documents\db.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
                SqlConnection con = new SqlConnection(conString);
                
         
                try
                {
                    //Form1 frm2 = new Form1();
                    string clientIP = Form1.curIP;


                    con.Open();
                    //MessageBox.Show("Connection Open ! ");
                    string query = "SELECT count(IP) from BlackList WHERE IP='" + clientIP + "'";


                    SqlCommand cmd = new SqlCommand(query, con);
                    int rowCount = 0;
                    rowCount = (int)cmd.ExecuteScalar();
                    string wlq = "SELECT count(IP) from WhiteList WHERE IP='" + clientIP + "'";
                    SqlCommand cmd_wl = new SqlCommand(wlq, con);
                    int rowcount_wl = 0;
                    rowcount_wl = (int)cmd_wl.ExecuteScalar();


                    if (rowCount > 0)
                    {
                        Byte[] sendBytes = Encoding.ASCII.GetBytes("This IP is black Listed.Please retry after a few seconds.");
                        networkStream.Write(sendBytes, 0, sendBytes.Length);
               
                    }
                        


                    else
                    {
                        if (rowcount_wl > 0)
                    {
                        Byte[] sendBytes = Encoding.ASCII.GetBytes("This ip is present in white list.");
                        networkStream.Write(sendBytes, 0, sendBytes.Length);
                    }
                    else
                    {
                        //Byte[] sendBytes = Encoding.ASCII.GetBytes("This ip is not present in white list.");
                        //networkStream.Write(sendBytes, 0, sendBytes.Length);
                    }
                    DateTime curDT = System.DateTime.Now;
                    int cr_no = 1;


                    string check_ip_in_rule = "SELECT count(IP) from Rule1 WHERE IP LIKE'" + clientIP + "'";
                    SqlCommand cmd_check_ip_in_rule = new SqlCommand(check_ip_in_rule, con);
                    int rule_rowCount = 0;
                    rule_rowCount = (int)cmd_check_ip_in_rule.ExecuteScalar();
                    if (rule_rowCount <= 0)
                    {
                        string q_insert_rule = "INSERT INTO Rule1 (IP,time,Critical_Number) VALUES('" + clientIP + "','" + curDT + "','" + cr_no + "')";
                        SqlCommand cmd_insert_rule = new SqlCommand(q_insert_rule, con);
                        cmd_insert_rule.ExecuteNonQuery();
                    }
                    else
                    {


                        string q_select_crNo = "SELECT Critical_Number from Rule1 Where IP='" + clientIP + "'";
                        SqlCommand cmd_select_crNo = new SqlCommand(q_select_crNo, con);
                        SqlDataReader readCrno = cmd_select_crNo.ExecuteReader();
                        int crNo = 0;
                        if (readCrno.HasRows)
                        {
                            while (readCrno.Read())
                            {
                                crNo = readCrno.GetInt32(0);


                            }
                        }
                        readCrno.Close();
                        double seconds;
                        string q_rule = "SELECT time from Rule1 Where IP='" + clientIP + "'";
                        SqlCommand cmd_rule = new SqlCommand(q_rule, con);


                        SqlDataReader reader = cmd_rule.ExecuteReader();
                        DateTime dd = new DateTime();
                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {


                                dd = reader.GetDateTime(0);
                            }
                        }




                        reader.Close();


                        TimeSpan ts = (curDT - dd);


                        seconds = ts.TotalSeconds;
                        //MessageBox.Show(seconds.ToString());


                        if (seconds < 60)
                        {
                            newCritical_No = crNo + 1;
                            string q_update_rule = "UPDATE Rule1 SET Critical_Number='" + newCritical_No + "' where IP='" + clientIP + "'";
                            SqlCommand cmd_update_rule = new SqlCommand(q_update_rule, con);
                            cmd_update_rule.ExecuteNonQuery();
                        }
                        else
                        {
                            DateTime dt = new DateTime();
                            dt = DateTime.Now;
                            string update_rule1_time = "UPDATE RULE1 SET Critical_Number=1,time='" + dt + "' WHERE IP='" + clientIP + "'";
                            SqlCommand update_time = new SqlCommand(update_rule1_time, con);
                            update_time.ExecuteNonQuery();


                        }
                        //int load = frm2.cpuLoad;
                        int load = 81;
                        if (seconds < 60 && newCritical_No > 2)
                        {
                            Byte[] sendBytes = Encoding.ASCII.GetBytes("sorry u r temporarily blocked.You can not send more than 3 requests within 60 seconds");
                            networkStream.Write(sendBytes, 0, sendBytes.Length);
                            string insert_blist = "INSERT INTO BlackList(IP) VALUES('" + clientIP + "')";
                            SqlCommand insert_blist_cmd = new SqlCommand(insert_blist, con);
                            insert_blist_cmd.ExecuteNonQuery();
                        }
                        if (load >81)
                        {


                            if (seconds < 60 && newCritical_No > 1)
                            {
                                Byte[] sendBytes = Encoding.ASCII.GetBytes("You are blocked because of load on server is above 80%");
                                networkStream.Write(sendBytes, 0, sendBytes.Length);
                                string bl_insert_load = "INSERT INTO BlackList(IP) VALUES('" + clientIP + "')";
                                SqlCommand cmd_insertbl_load = new SqlCommand(bl_insert_load, con);
                                cmd_insertbl_load.ExecuteNonQuery();
                            }
                        }
                        if (load > 81 && newCritical_No > 0 && seconds < 60)
                        {
                            Byte[] sendBytes = Encoding.ASCII.GetBytes("You are blocked because of load on server is above 80 and still over");
                            networkStream.Write(sendBytes, 0, sendBytes.Length);
                            string bl_insert_load1 = "INSERT INTO BlackList(IP) VALUES('" + clientIP + "')";
                            SqlCommand cmd_insertbl_load1 = new SqlCommand(bl_insert_load1, con);
                            cmd_insertbl_load1.ExecuteNonQuery();
                        }
                        else {
                            //send the data back to client.
                            Byte[] sendBytes2 = Encoding.ASCII.GetBytes("Congratulation!you are registered successfully with\nIMPI:"+arr[0]+"\nIMPU:"+arr[1]);
                            networkStream.Write(sendBytes2, 0, sendBytes2.Length);
                        }


                    }
                        con.Close();
                        //................job ends................//
                   
                    }
                }




                catch (Exception exp)
                {
                    throw;
                }
       


            
            
              
                networkStream.Flush();
            }
            catch (Exception ex)
            {
                throw;
            }


            this.WaitForRequest();
        }
    }
}
 
Last edited by a moderator:

jmcilhinney

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
3,209
Location
Sydney, Australia
Programming Experience
10+
I can guarantee you that it's not for no reason. There will be a very good reason but I'm not going to look through all that code to work out what you can tell me yourself. The question is, where does reality differ from expectation? Have you debugged the code at all? If not then you need to go back and do that first. Use breakpoints at appropriate places to halt execution and then step through the code line by line. You have various tools at your disposal to determine the state of the application at any particular point. As soon as that state is not what you expect, you've found an issue. If you're unable to work out the specific cause or the solution, then you post back here and tell us what you're debugging has revealed so that we know where in the to look.
 
Top Bottom