2017-12-28 52 views
-1

私は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); 
      } 
     } 
    } 
+0

これまでに書いたコード –

+0

はミリ秒ごとに投稿してください。これはDDoSプログラムですか? – Steve

+0

@Steveは実際にはこれを意味します: 私はカウンタを持っており、値10を加えてクライアントに送信し、クライアントはクライアントの値を連続したクライアントフォームにリアルタイムで書き込んで更新します。 –

答えて

0

:あなたが使用するタイマは正常に動作する必要があります。コードには間違いがあります。

  1. 上記のコードでは、InitTimer関数を呼び出していません。したがって、タイマーは起動していません。 StartServerを呼び出したコンストラクタでこれを呼び出すことができます。
  2. timer1.Interval = 6000000;応答が長すぎる100分です。それを6000すなわち6秒に変更したいかもしれません。 WorkCounter機能変更の送信ラインで
  3.  _clientSocket.BeginSend(_buffer, 0,_buffer.Length,SocketFlags.None, new AsyncCallback(SendCallBack), null); 
    

    あなたはクライアントソケットではないサーバソケットを使用して、それを送信する必要がありますので、あなたがクライアントソケットにデータを送信しているように。サーバソケットはリスティングにのみ使用されます。クライアントソケットはクライアントとの通信に使用されます

関連する問題