服务器客户通信在时间间隔内发送和接收数据



我正在尝试使用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:UsersBusraDesktopCommunicationAsyncSocketCommunicationAsyncSocketbinDebugTCP 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 +" "+"rn";
            });
            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 + "rn";
            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 + " " + "rn";
                });
                this.Invoke(invoker);
            }
        }
    }

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

  1. 您没有在上述代码中的任何位置调用InitTimer功能。因此,计时器没有启动。您可能想在构造函数中调用它,该构建器称为StartServer
  2. timer1.Interval = 6000000;它的100分钟太长了。您可能想将其更改为6000,即6秒
  3. WorkCounter功能中,将线更改为

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

    当您在客户端套接字上发送数据时,应使用客户端套接字而非服务器套接字发送它。服务器插座仅用于列表。客户插座用于与客户端通信

最新更新