I have mini project about client-server connection and i'm using TCP Socket to do a connection. The server wants to know if a client has a 'notepad.exe' application running on the client machine.

I already have list of running process on client machine, and i have an algorithm to detect if Notepad is already running or not.

So, I think there will be a 'Refresh' button on server in order to force Client Side to send data (Notepad application status) to Server , but still in Server Side. Do you get my point ? Sent Data is a string data, e.g. "Notepad is already running", or "Notepad has not started yet".

Just Like my Subject Title, I want to know How to send data from client to server via server side ? Could you please give me some Simple Application about forcing client to send data to server via server side. Urgently Needed

Thanks for any help

Best Regards
Yefta Adiya - Indonesia -
C# Developer

Recommended Answers

All 5 Replies

Hi.. It's Me the Thread Starter.

First of All, I'm sorry about my Mistype subject. It should be UDP connection not TCP connection. It's my stupid fault :'(

Anyway, Here's my Code that i have
SERVER SIDE

//The commands for interaction between the server and the client
    enum Command
    {
        Login,      //Log into the server
        Logout,     //Logout of the server
        Null        //No command
    }

    public partial class KioskMonitoringServer : Form
    {
        struct ClientInfo
        {
            public EndPoint endpoint;   //Socket of the client
            public string strName;      //Name by which the client logged into the server
            public string strClientStatus;
            public string strClientOS;
            public string strClientApp;
        }

        //The collection of all clients logged into the room (an array of type ClientInfo)
        ArrayList clientList;

        //The main socket on which the server listens to the clients
        Socket serverSocket;

        byte[] byteData = new byte[1024];

        public KioskMonitoringServer()
        {
            InitializeComponent();
            clientList = new ArrayList();
        }

        private void btnListening_Click(object sender, EventArgs e)
        {
            try
            {
                CheckForIllegalCrossThreadCalls = false;

                //i'm using UDP sockets
                serverSocket = new Socket(AddressFamily.InterNetwork,
                    SocketType.Dgram, ProtocolType.Udp);

                //Assign the any IP of the machine and listen on port on TextBox
                IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, Convert.ToInt32(txtPort.Text));

                //Bind this address to the server
                serverSocket.Bind(ipEndPoint);

                IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
                //The epSender identifies the incoming clients
                EndPoint epSender = (EndPoint)ipeSender;

                //Start receiving data
                serverSocket.BeginReceiveFrom(byteData, 0, byteData.Length,
                    SocketFlags.None, ref epSender, new AsyncCallback(OnReceive), epSender);

                txtLog.AppendText("Start Listening on " + txtPort.Text + "\n");
                btnListening.Enabled = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "SGSServerUDP",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }     
        }

        private void OnReceive(IAsyncResult ar)
        {
            memoClientDetail.Clear();
            try
            {
                IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
                EndPoint epSender = (EndPoint)ipeSender;

                serverSocket.EndReceiveFrom(ar, ref epSender);

                //Transform the array of bytes received from the user into an
                //intelligent form of object Data
                Data msgReceived = new Data(byteData);

                //We will send this object in response the users request
                Data msgToSend = new Data();

                byte[] message;

                switch (msgReceived.cmdCommand)
                {
                    case Command.Login:

                        //When a user logs in to the server then we add her to our
                        //list of clients

                        ClientInfo clientInfo = new ClientInfo();
                        clientInfo.endpoint = epSender;
                        clientInfo.strName = msgReceived.strName;
                        clientInfo.strClientStatus = msgReceived.strClientStatus;
                        clientInfo.strClientOS = msgReceived.strClientOS;
                        clientInfo.strClientApp = msgReceived.strClientApp;
                        
                        clientList.Add(clientInfo);

                        listClient.Items.Add(msgReceived.strName);
                        memoClientDetail.AppendText(msgReceived.strClientStatus);
                        memoClientDetail.AppendText(msgReceived.strClientOS);
                        memoClientDetail.AppendText(msgReceived.strClientApp);
                        break;

                    case Command.Logout:

                        //When a user wants to log out of the server then we search for her 
                        //in the list of clients and close the corresponding connection

                        int nIndex = 0;
                        foreach (ClientInfo client in clientList)
                        {
                            if (client.strName == msgReceived.strName)
                            {
                                clientList.RemoveAt(nIndex);

                                break;
                            }
                            ++nIndex;
                        }

                        listClient.Items.Remove(msgReceived.strName);
                        break;
                }

                txtLog.AppendText(msgToSend.strMessage + "\r\n");

                serverSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref epSender, new AsyncCallback(OnReceive), epSender);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "SGSServerUDP", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

CLIENT SIDE

enum Command
    {
        Login,      //Log into the server
        Logout,     //Logout of the server
        Null        //No command
    }

    public partial class KioskMonitoringClient : Form
    {
        public Socket clientSocket;
        public EndPoint epServer;
        public string strName;
        public string m_ApplicationName = "Notepad";
        public bool m_ApplicationIsRunning = false;

        public KioskMonitoringClient()
        {
            InitializeComponent();
        }

        private ArrayList GetProcesses() //This method is used for Generating Current running process
        {
            ArrayList procList = new ArrayList();
            try
            {
                Process[] process = Process.GetProcesses();
                foreach (Process proc in process)
                {
                    procList.Add(proc);
                }
                return procList;
            }
            catch (Exception)
            {
                return null;
            }
        }

        private string CheckRunningProcess(string process) // this Function is used for checking if an application (i'm using notepad.exe) is running or not
        {
            try
            {
                this.SuspendLayout();
                m_ApplicationIsRunning = false;
                ArrayList arrProcess = new ArrayList();
                arrProcess = this.GetProcesses();

                Process proc;
                for (int i = 0; i < arrProcess.Count; i++)
                {
                    proc = new Process();
                    proc = (Process)arrProcess[i];
                    if (String.Compare(process.ToUpper(), proc.ProcessName.ToUpper()) == 0)
                    {
                        m_ApplicationIsRunning = true;
                        break;
                    }
                }
                if (m_ApplicationIsRunning)
                    return "Running";
                else
                    return "Not started";
            }
            catch (Exception)
            {
                return "Not started";
            }
        }

        private void btnConnect_Click(object sender, EventArgs e) // Connecting to server
        {
            strName = Dns.GetHostName(); //Get Computer name
            try
            {
                //Using UDP sockets
                clientSocket = new Socket(AddressFamily.InterNetwork,
                    SocketType.Dgram, ProtocolType.Udp);

                //IP address of the server machine
                IPAddress ipAddress = IPAddress.Parse(txtServerIP.Text);
                //Server is listening on current txtServerPort.Text
                IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, Convert.ToInt32(txtServerPort.Text));

                epServer = (EndPoint)ipEndPoint;

                Data msgToSend = new Data();
                OperatingSystemInfo osInfo = new OperatingSystemInfo();

                #region " Send Data"
                msgToSend.cmdCommand = Command.Login;
                msgToSend.strName = strName;
                msgToSend.strMessage = null;
                msgToSend.strClientStatus = "Client Status : Online\n";
                msgToSend.strClientOS = "Operating System Info : " + osInfo.GetOSName() + osInfo.GetOSProductType() + osInfo.GetOSServicePack() + "\n";
                msgToSend.strClientApp = "Notepad Application Status : " + this.CheckRunningProcess(m_ApplicationName) + "\n";
                #endregion

                byte[] byteData = msgToSend.ToByte();

                //Login to the server
                clientSocket.BeginSendTo(byteData, 0, byteData.Length,
                    SocketFlags.None, epServer, new AsyncCallback(OnSend), null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "SGSclient",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void OnSend(IAsyncResult ar)
        {
            try
            {
                clientSocket.EndSend(ar);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "SGSclient", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void KioskMonitoringClient_Load(object sender, EventArgs e)
        {
            CheckForIllegalCrossThreadCalls = false;
        }

        private void KioskMonitoringClient_FormClosing(object sender, FormClosingEventArgs e) // Logout from server
        {
            try
            {
                //Send a message to logout of the server
                Data msgToSend = new Data();
                msgToSend.cmdCommand = Command.Logout;
                msgToSend.strName = strName;
                msgToSend.strMessage = null;

                byte[] b = msgToSend.ToByte();
                clientSocket.SendTo(b, 0, b.Length, SocketFlags.None, epServer);
                clientSocket.Close();
            }
            catch (ObjectDisposedException)
            { }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "SGSclient: " + strName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

OK, so, whats the problem you have?
The most important thing to understand is that UDP is connectionless.. so theres no guarantee it is received.

It's OK about connectionless.

Here's the problem.

Right now i'm able to send data from client to server via client side. Using OnSend(IAsyncResult ar) on Client Side and OnReceive(IAsyncResult ar) on Server Side.

But, The problem is, Is it possible to send data from client to server via server side ? Or in other word, Is is possible to me (server) forces the client to send data ?

Let's brainstorming. I'm using Windows Form project right now. I think there will be a 'Refresh' button on Server Side UI in order to make a client (which is currently connected) send data to server. But, .. How ??

However, I have noob method to solve this problem, Which is I'm using timer on Client side to send data periodically according to the timer setting. But, i think it is not an effective way to solve this problem because the client has to send data over and over without request from server.

Thanks for any responses...

only in the sense of your server can say "I want data now" and your client can do the sending..
but again as its connectionless theres no guarentee the client would get it over UDP and no guarentee even if the client responds that the server would get it

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.