-1

I'm trying to make asynchronous client server program with C#. I wanna to send data every milliseconds to client without click send button. How can I do this ? My program has been already send and receive message between client and server when clicking send button. I am trying to modify this.

Server Side

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Diagnostics;



namespace TCP_Server
{

    public partial class ServerForm : Form
    {

        private Socket _serverSocket;
        private Socket _clientSocket;
        private byte[] _buffer;
        private static int counter = 0;
        private Timer timer1; 


        public ServerForm()
        {
            string path = @"C:\Users\Busra\Desktop\CommunicationAsyncSocket\CommunicationAsyncSocket\bin\Debug\TCP Client.exe";
            Process.Start(path);
            InitializeComponent();
            StartServer();
        }

        private void StartServer()
        {
            try
            {
                _serverSocket = new Socket(AddressFamily.InterNetwork,
                    SocketType.Stream,
                    ProtocolType.Tcp);
                _serverSocket.Bind(new IPEndPoint(IPAddress.Any, 3333));
                _serverSocket.Listen(0);
                _serverSocket.BeginAccept(new AsyncCallback(AcceptCallBack),
                    null);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void AcceptCallBack(IAsyncResult ar)
        {
            try
            {
                _clientSocket = _serverSocket.EndAccept(ar);
                _buffer = new byte[_clientSocket.ReceiveBufferSize];
                _clientSocket.BeginReceive(_buffer, 0, _buffer.Length,
                    SocketFlags.None, new AsyncCallback(RecieveCallBack),null);

                AppendToTextBox("Client has connected..");
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void RecieveCallBack(IAsyncResult ar)
        {
            try
            {
                int received = _clientSocket.EndReceive(ar);
                Array.Resize(ref _buffer, received);
                string txt = Encoding.ASCII.GetString(_buffer);
                AppendToTextBox(">>Client: "+txt);
                Array.Resize(ref _buffer, _clientSocket.ReceiveBufferSize);
                _clientSocket.BeginReceive(_buffer, 0, _buffer.Length,
                  SocketFlags.None, new AsyncCallback(RecieveCallBack), null);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void AppendToTextBox(string text)
        {
            MethodInvoker invoker = new MethodInvoker(delegate
            {
                textBox.Text += " " + text +" "+"\r\n";

            });
            this.Invoke(invoker);
        }

        public void InitTimer()
        {
            timer1 = new Timer();
            timer1.Tick += new EventHandler(timer2_Tick);
            timer1.Interval = 6000000; // in miliseconds
            timer1.Start();
        }

        public void WorkCounter()
        {
            counter += 10;
            textBox_counter.Text = counter + "\r\n";
            try
            {
                byte[] _buffer = Encoding.ASCII.GetBytes(textBox_counter.Text); 
                _serverSocket.BeginSend(_buffer, 0, _buffer.Length,
                    SocketFlags.None, new AsyncCallback(SendCallBack), null);
            }
            catch (SocketException ex)
            { }//server closed
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        private void SendCallBack(IAsyncResult ar)
        {
            try
            {
                _serverSocket.EndSend(ar);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            WorkCounter();
        }
    }
}

Client Side


 using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;

    namespace CommunicationAsyncSocket
    {
        public partial class ClientForm : Form
        {
            private Socket _clientSocket;
            private Socket _serverSocket;
            private byte[] _buffer;


            public ClientForm()
            {
                InitializeComponent();
            }

            private void btn_connect_Click(object sender, EventArgs e)
            {
                try
                {
                    _clientSocket = new Socket(AddressFamily.InterNetwork,
                        SocketType.Stream, ProtocolType.Tcp);
                    _clientSocket.BeginConnect(new IPEndPoint(IPAddress.Loopback, 3333),
                        new AsyncCallback(ConnectCallBack),null);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

            private void ConnectCallBack(IAsyncResult ar)
            {
                try
                {
                    _clientSocket.EndConnect(ar);
                    btn_send.Enabled = true;


                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);

                }
            }

            private void btn_send_Click(object sender, EventArgs e)
            {
                try
                {
                    byte[] _buffer = Encoding.ASCII.GetBytes(textBox.Text+" "+textBox1.Text);
                    textBox1.Text = " "; textBox.Text = " ";
                    _clientSocket.BeginSend(_buffer, 0, _buffer.Length,
                        SocketFlags.None, new AsyncCallback(SendCallBack), null);
                }
                catch (SocketException ex)
                {   }//server closed
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

            }

            private void SendCallBack(IAsyncResult ar)
            {
                try
                {
                    _clientSocket.EndSend(ar);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

            private void AcceptCallBack(IAsyncResult ar)
            {
                try
                {
                    _serverSocket = _clientSocket.EndAccept(ar);
                    _buffer = new byte[_serverSocket.ReceiveBufferSize];
                    _serverSocket.BeginReceive(_buffer, 0, _buffer.Length,
                        SocketFlags.None, new AsyncCallback(RecieveCallBack), null);

                    AppendToTextBox("Server has connected..");
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

            private void RecieveCallBack(IAsyncResult ar)
            {
                try
                {
                    int received = _serverSocket.EndReceive(ar);
                    Array.Resize(ref _buffer, received);
                    string txt = Encoding.ASCII.GetString(_buffer);
                    AppendToTextBox(">>Server: " + txt);
                    Array.Resize(ref _buffer, _serverSocket.ReceiveBufferSize);
                    _serverSocket.BeginReceive(_buffer, 0, _buffer.Length,
                      SocketFlags.None, new AsyncCallback(RecieveCallBack), null);
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            private void AppendToTextBox(string text)
            {
                MethodInvoker invoker = new MethodInvoker(delegate
                {
                    textBoxCounter.Text += " " + text + " " + "\r\n";

                });
                this.Invoke(invoker);
            }
        }
    }
Büşra GÜL
  • 323
  • 1
  • 4
  • 16
  • Please post the code you wrote so far – Souvik Ghosh Dec 28 '17 at 17:08
  • every millisecond. is this a DDoS program? – Steve Dec 28 '17 at 17:09
  • @Steve actually I mean this: I have a counter and I will add a value of 10 and send it to the client and the client will write and update the value of the client in real time on a continuous client form. – Büşra GÜL Dec 28 '17 at 17:16
  • Your question is too broad. Stack Overflow already has plenty of questions with answers explaining how to perform some arbitrary operation at some arbitrary interval (typically using a timer object or a loop in an `async` method with `Task.Delay()`). Have you tried _anything_? What _specifically_ do you need help with? – Peter Duniho Dec 29 '17 at 00:13

1 Answers1

0

In the server code: The timer you used should work fine. but there are some mistake in code.

  1. You are not calling InitTimer function anywhere in the above code. So the timer is not starting. You might wanna call this in constructor where you called StartServer.
  2. timer1.Interval = 6000000; its 100 minutes which is too long to respond. you might wanna change it to 6000 i.e, 6 sec.
  3. In the WorkCounter function change sending line to

          _clientSocket.BeginSend(_buffer, 0,_buffer.Length,SocketFlags.None, new AsyncCallback(SendCallBack), null);
    

    as you are sending data on client socket so you should send it by using the client socket not server socket. Server socket is used only for listing. And client socket is use to communicate with client