Server-Client 通信按时间间隔发送和接收数据

Posted

技术标签:

【中文标题】Server-Client 通信按时间间隔发送和接收数据【英文标题】:Server-Client communication send and receive data in time interval 【发布时间】:2017-12-28 17:07:03 【问题描述】:

我正在尝试使用 C# 制作异步客户端服务器程序。 我想每毫秒向客户端发送一次数据,而无需单击发送按钮。我怎样才能做到这一点 ? 单击发送按钮时,我的程序已经在客户端和服务器之间发送和接收消息。我正在尝试修改它。

服务器端

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();
        
    

客户端


 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);
            
        
    

【问题讨论】:

请贴出你目前写的代码 每毫秒。这是 DDoS 程序吗? @Steve 实际上我的意思是:我有一个计数器,我将添加一个值 10 并将其发送给客户端,客户端将实时写入和更新客户端的值连续的客户形式。 你的问题太宽泛了。 Stack Overflow 已经有很多问题的答案解释了如何以任意时间间隔执行任意操作(通常使用定时器对象或 async 方法中的循环和 Task.Delay())。你有没有尝试过任何东西?您具体在哪些方面需要帮助? 【参考方案1】:

在服务器代码中:您使用的计时器应该可以正常工作。但是代码有一些错误。

    您没有在上述代码的任何地方调用InitTimer 函数。所以计时器没有启动。您可能想在您调用StartServer 的构造函数中调用它。 timer1.Interval = 6000000; 100 分钟太长了,无法回复。您可能想将其更改为 6000,即 6 秒。

    WorkCounter函数中将发送行改为

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

    当您在客户端套接字上发送数据时,您应该使用客户端套接字而不是服务器套接字来发送数据。服务器套接字仅用于列表。客户端套接字用于与客户端通信

【讨论】:

以上是关于Server-Client 通信按时间间隔发送和接收数据的主要内容,如果未能解决你的问题,请参考以下文章

线程和 java / Server-Client 程序

ChromeCast 如何与接收方应用和发送方应用通信?

异步传输模式与同步传输模式的区别

安全通信的特性

RabbitMQ消息队列

如何获得 ActiveMQ - 单个发送方和接收方的 FIFO 要求?