none
TCP Server with Data Received Event

    Dotaz

  • Hello everyone, 

    I tried to complete TCP server in windows form application. I have class Server, which creates TCP Listener and waiting for clients requests. And class Form1, where I want to display received values. But I think, that event is no working. Could someone tell me, where can be a problem? Thaks a lot.

    Program.cs: 

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Windows.Forms;
    
    namespace TCP_Monitor
    {
        static class Program
        {
            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            [STAThread]
            static void Main()
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
        }
    }
    

    Server.cs: 

    using System;
    using System.Text;
    using System.Net.Sockets;           
    using System.Threading;             
    using System.Net;                   
    
    namespace TCP_Monitor
    {
        class Server
        {   
            private TcpListener tcpListener;
            
            private Thread listenThread;
            
            public string Rx_Data;
    
            public event EventHandler Received;
    
            public Server()
            {
                this.tcpListener = new TcpListener(IPAddress.Any, 2032);
    
                this.listenThread = new Thread(new ThreadStart(ListenForClients));
    
                this.listenThread.Start();
            }
    
    
            private void ListenForClients()
            {
                this.tcpListener.Start();
    
                while (true)
                {
                    TcpClient client = this.tcpListener.AcceptTcpClient();
    
                    Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
    
                    clientThread.Start(client);
                }
            }
    
            protected virtual void IsDataReceived(EventArgs e)
            {
                if (Received != null)
                    Received(this, e);
            }
    
            private void HandleClientComm(object client)
            {
                TcpClient tcpClient = (TcpClient)client;
    
                NetworkStream clientStream = tcpClient.GetStream();
    
                byte[] message = new byte[4096];
    
                int bytesRead;
    
                while (true)
                {
                    bytesRead = 0;
    
                    try
                    {
                        bytesRead = clientStream.Read(message, 0, 4096);
                    }
                    catch
                    {
                        break;
                    }
    
                    if (bytesRead == 0)
                    {
                        break;
                    }
    
                    ASCIIEncoding encoder = new ASCIIEncoding();
    
                    //GetString - prevod rozsahu bajtu v poli do string
    
                    Rx_Data = encoder.GetString(message, 0, bytesRead);
    
                    IsDataReceived(EventArgs.Empty);
                }
            }
        }
    }
    

    Form1.cs: 

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    
    namespace TCP_Monitor
    {
        public partial class Form1 : Form
        {
            Server server = new Server();
    
            public Form1()
            {
                InitializeComponent();
    
                server.Received += new EventHandler(server_Received);    
    
            }
    
            public void server_Received(object sender, EventArgs e)
            {
                textBox1.Text = server.Rx_Data;
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                
            }       
            
            
        }
    }
    

    Form1.Designer.cs:

    namespace TCP_Monitor
    {
        partial class Form1
        {
            /// <summary>
            /// Required designer variable.
            /// </summary>
            private System.ComponentModel.IContainer components = null;
    
            /// <summary>
            /// Clean up any resources being used.
            /// </summary>
            /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
            protected override void Dispose(bool disposing)
            {
                if (disposing && (components != null))
                {
                    components.Dispose();
                }
                base.Dispose(disposing);
            }
    
            #region Windows Form Designer generated code
    
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {
                this.textBox1 = new System.Windows.Forms.TextBox();
                this.button1 = new System.Windows.Forms.Button();
                this.SuspendLayout();
                // 
                // textBox1
                // 
                this.textBox1.BackColor = System.Drawing.SystemColors.ControlLightLight;
                this.textBox1.Location = new System.Drawing.Point(12, 12);
                this.textBox1.Multiline = true;
                this.textBox1.Name = "textBox1";
                this.textBox1.ReadOnly = true;
                this.textBox1.Size = new System.Drawing.Size(638, 129);
                this.textBox1.TabIndex = 0;
                // 
                // button1
                // 
                this.button1.Location = new System.Drawing.Point(142, 276);
                this.button1.Name = "button1";
                this.button1.Size = new System.Drawing.Size(75, 23);
                this.button1.TabIndex = 1;
                this.button1.Text = "button1";
                this.button1.UseVisualStyleBackColor = true;
                this.button1.Click += new System.EventHandler(this.button1_Click);
                // 
                // Form1
                // 
                this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
                this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
                this.ClientSize = new System.Drawing.Size(662, 371);
                this.Controls.Add(this.button1);
                this.Controls.Add(this.textBox1);
                this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
                this.Name = "Form1";
                this.Text = "TCP Monitor v1.0";
                this.ResumeLayout(false);
                this.PerformLayout();
    
            }
    
            #endregion
    
            private System.Windows.Forms.TextBox textBox1;
            private System.Windows.Forms.Button button1;
    
        }
    }
    
    

    25. února 2013 8:47

Všechny reakce

  • Aha, koukám že to je český fórum :D. Mám prostě problém s tím předat přijatá data ze třídy Server do textBox1. Tak aby se tato hodnota měnila podle toho, jaká data budou přijata. Vytvořil jsem tam i event, který by se měl spustit po přijetí zprávy od klienta, ale bohužel se mi žádné hodnoty v textboxu nezobrazují. Díky za jakoukoli pomoc. 
    25. února 2013 10:57