简体   繁体   English

PuTTy从服务器telnet接收数据,但不是我的C#程序

[英]PuTTy receives data from server telnet but not my C# program

I got a sample C# program (Client and Server) somewhere around the net. 我在网上某处有一个示例C#程序(客户端和服务器)。 It works well when communicating with each other, HOWEVER, the client doesn't work and so is my program (when trying to receive data from my microcontroller over the network via telnet). 当彼此通信时,它工作良好,但是,客户端不起作用,我的程序也是如此(当尝试通过telnet通过网络从微控制器接收数据时)。 When I try to use PuTTy, it works very well. 当我尝试使用PuTTy时,效果很好。 Here is my short whole codes for the client. 这是我为客户准备的完整的简短代码。 Please tell me what to do :) What's wrong with this code: 请告诉我该怎么做:)这段代码有什么问题:

edit and additional info: the C# program starts to receive the data IF and ONLY IF I run the PuTTy. 编辑和其他信息:如果我运行PuTTy,则C#程序开始接收数据。 Funny. 滑稽。 It seems the device only starts throwing the data to every clients when PuTTy is connected. 似乎只有在连接PuTTy后,设备才开始向每个客户端抛出数据。

What I want to get: Exactly what is printed in Putty screenshot: Q0.00W0.00X0.00Y0.00Z0.00 where 0.00 can be any value. 我想要得到什么: 实际在腻子屏幕截图中打印的内容是: Q0.00W0.00X0.00Y0.00Z0.00 ,其中0.00可以是任何值。 Look also at my C# program screenshot. 还要看我的C#程序屏幕截图。 It gets wrong format of string that is being sent :( 它发送的字符串格式错误:(

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net;                                   // Endpoint
using System.Net.Sockets;                           // Socket namespace
using System.Text;                                  // Text encoders

// Declare the delegate prototype to send data back to the form
delegate void AddMessage( string sNewMessage );


namespace ChatClient
{
    /// <summary>
    /// This form connects to a Socket server and Streams data to and from it.
    /// Note: The following has been ommitted.
    ///     1) Send button need to be grayed when conneciton is 
    ///        not active
    ///     2) Send button should gray when no text in the Message box.
    ///     3) Line feeds in the recieved data should be parsed into seperate
    ///        lines in the recieved data list
    ///     4) Read startup setting from a app.config file
    /// </summary>
    public class FormMain : System.Windows.Forms.Form
    {
        // My Attributes
        private Socket          m_sock;                     // Server connection
        private byte []         m_byBuff = new byte[256];   // Recieved data buffer
        private event AddMessage m_AddMessage;              // Add Message Event handler for Form

        // Wizard generated code
        private System.Windows.Forms.Button m_btnConnect;
        private System.Windows.Forms.TextBox m_tbServerAddress;
        private System.Windows.Forms.ListBox m_lbRecievedData;
        private System.Windows.Forms.TextBox m_tbMessage;
        private System.Windows.Forms.Button m_btnSend;
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.Container components = null;

        public FormMain()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            // Add Message Event handler for Form decoupling from input thread
            m_AddMessage = new AddMessage( OnAddMessage );


            //
            // TODO: Add any constructor code after InitializeComponent call
            //
        }

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if (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.m_tbServerAddress = new System.Windows.Forms.TextBox();
            this.m_tbMessage = new System.Windows.Forms.TextBox();
            this.m_btnConnect = new System.Windows.Forms.Button();
            this.m_lbRecievedData = new System.Windows.Forms.ListBox();
            this.m_btnSend = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // m_tbServerAddress
            // 
            this.m_tbServerAddress.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
                | System.Windows.Forms.AnchorStyles.Right);
            this.m_tbServerAddress.Location = new System.Drawing.Point(8, 8);
            this.m_tbServerAddress.Name = "m_tbServerAddress";
            this.m_tbServerAddress.Size = new System.Drawing.Size(204, 20);
            this.m_tbServerAddress.TabIndex = 1;
            this.m_tbServerAddress.Text = "192.168.0.8";
            // 
            // m_tbMessage
            // 
            this.m_tbMessage.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
                | System.Windows.Forms.AnchorStyles.Right);
            this.m_tbMessage.Location = new System.Drawing.Point(8, 37);
            this.m_tbMessage.Name = "m_tbMessage";
            this.m_tbMessage.Size = new System.Drawing.Size(205, 20);
            this.m_tbMessage.TabIndex = 3;
            this.m_tbMessage.Text = "";
            // 
            // m_btnConnect
            // 
            this.m_btnConnect.Anchor = (System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right);
            this.m_btnConnect.Location = new System.Drawing.Point(228, 8);
            this.m_btnConnect.Name = "m_btnConnect";
            this.m_btnConnect.TabIndex = 0;
            this.m_btnConnect.Text = "Connect";
            this.m_btnConnect.Click += new System.EventHandler(this.m_btnConnect_Click);
            // 
            // m_lbRecievedData
            // 
            this.m_lbRecievedData.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
                | System.Windows.Forms.AnchorStyles.Left) 
                | System.Windows.Forms.AnchorStyles.Right);
            this.m_lbRecievedData.IntegralHeight = false;
            this.m_lbRecievedData.Location = new System.Drawing.Point(0, 66);
            this.m_lbRecievedData.Name = "m_lbRecievedData";
            this.m_lbRecievedData.Size = new System.Drawing.Size(311, 220);
            this.m_lbRecievedData.TabIndex = 2;
            // 
            // m_btnSend
            // 
            this.m_btnSend.Anchor = (System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right);
            this.m_btnSend.Location = new System.Drawing.Point(228, 36);
            this.m_btnSend.Name = "m_btnSend";
            this.m_btnSend.TabIndex = 4;
            this.m_btnSend.Text = "Send";
            this.m_btnSend.Click += new System.EventHandler(this.m_btnSend_Click);
            // 
            // FormMain
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(312, 287);
            this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                          this.m_btnSend,
                                                                          this.m_tbMessage,
                                                                          this.m_lbRecievedData,
                                                                          this.m_tbServerAddress,
                                                                          this.m_btnConnect});
            this.Name = "FormMain";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
            this.Text = "Form1";
            this.Closing += new System.ComponentModel.CancelEventHandler(this.FormMain_Closing);
            this.ResumeLayout(false);

        }
        #endregion

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main() 
        {
            Application.Run(new FormMain());
        }

        /// <summary>
        /// Connect button pressed. Attempt a connection to the server and 
        /// setup Recieved data callback
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void m_btnConnect_Click(object sender, System.EventArgs e)
        {
            Cursor cursor = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                // Close the socket if it is still open
                if( m_sock != null && m_sock.Connected )
                {
                    m_sock.Shutdown( SocketShutdown.Both );
                    System.Threading.Thread.Sleep( 10 );
                    m_sock.Close();
                }

                // Create the socket object
                m_sock = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp ); 

                // Define the Server address and port
                IPEndPoint epServer = new IPEndPoint(  IPAddress.Parse( m_tbServerAddress.Text ), 23 );

                // Connect to the server blocking method and setup callback for recieved data
                // m_sock.Connect( epServer );
                // SetupRecieveCallback( m_sock );

                // Connect to server non-Blocking method
                m_sock.Blocking = false;
                AsyncCallback onconnect = new AsyncCallback( OnConnect );
                m_sock.BeginConnect( epServer, onconnect, m_sock );
            }
            catch( Exception ex )
            {
                MessageBox.Show( this, ex.Message, "Server Connect failed!" );
            }
            Cursor.Current = cursor;
        }

        public void OnConnect( IAsyncResult ar )
        {
            // Socket was the passed in object
            Socket sock = (Socket)ar.AsyncState;

            // Check if we were sucessfull
            try
            {
                //sock.EndConnect( ar );
                if( sock.Connected )
                    SetupRecieveCallback( sock );
                else
                    MessageBox.Show( this, "Unable to connect to remote machine", "Connect Failed!" );
            }
            catch( Exception ex )
            {
                MessageBox.Show( this, ex.Message, "Unusual error during Connect!" );
            }
        }

        /// <summary>
        /// Get the new data and send it out to all other connections. 
        /// Note: If not data was recieved the connection has probably 
        /// died.
        /// </summary>
        /// <param name="ar"></param>
        public void OnRecievedData( IAsyncResult ar )
        {
            // Socket was the passed in object
            Socket sock = (Socket)ar.AsyncState;

            // Check if we got any data
            try
            {
                int nBytesRec = sock.EndReceive( ar );
                if( nBytesRec > 0 )
                {
                    // Wrote the data to the List
                    string sRecieved = Encoding.ASCII.GetString( m_byBuff, 0, nBytesRec );

                    // WARNING : The following line is NOT thread safe. Invoke is
                    // m_lbRecievedData.Items.Add( sRecieved );
                    Invoke( m_AddMessage, new string [] { sRecieved } );

                    // If the connection is still usable restablish the callback
                    SetupRecieveCallback( sock );
                }
                else
                {
                    // If no data was recieved then the connection is probably dead
                    Console.WriteLine( "Client {0}, disconnected", sock.RemoteEndPoint );
                    sock.Shutdown( SocketShutdown.Both );
                    sock.Close();
                }
            }
            catch( Exception ex )
            {
                MessageBox.Show( this, ex.Message, "Unusual error druing Recieve!" );
            }
        }

        public void OnAddMessage( string sMessage )
        {
            m_lbRecievedData.Items.Add( sMessage );
        }



        /// <summary>
        /// Setup the callback for recieved data and loss of conneciton
        /// </summary>
        public void SetupRecieveCallback( Socket sock )
        {
            try
            {
                AsyncCallback recieveData = new AsyncCallback( OnRecievedData );
                sock.BeginReceive( m_byBuff, 0, m_byBuff.Length, SocketFlags.None, recieveData, sock );
            }
            catch( Exception ex )
            {
                MessageBox.Show( this, ex.Message, "Setup Recieve Callback failed!" );
            }
        }

        /// <summary>
        /// Close the Socket connection bofore going home
        /// </summary>
        private void FormMain_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if( m_sock != null && m_sock.Connected )
            {
                m_sock.Shutdown( SocketShutdown.Both );
                m_sock.Close();
            }
        }

        /// <summary>
        /// Send the Message in the Message area. Only do this if we are connected
        /// </summary>
        private void m_btnSend_Click(object sender, System.EventArgs e)
        {
            // Check we are connected
            if( m_sock == null || !m_sock.Connected )
            {
                MessageBox.Show( this, "Must be connected to Send a message" );
                return;
            }

            // Read the message from the text box and send it
            try
            {       
                // Convert to byte array and send.
                Byte[] byteDateLine = Encoding.ASCII.GetBytes( m_tbMessage.Text.ToCharArray() );
                m_sock.Send( byteDateLine, byteDateLine.Length, 0 );
            }
            catch( Exception ex )
            {
                MessageBox.Show( this, ex.Message, "Send Message Failed!" );
            }
        }
    }
}

在此处输入图片说明

Ok, solved! 好,解决了! my microcontroller has a certain code that detects first if there is a client available. 我的微控制器具有确定的代码,该代码首先检测是否有可用的客户端。 Since my C# program just connects to the SERVER (the microcontroller) and waits for receiving the data, the server doesn't recognize the C# program as a client lol. 由于我的C#程序仅连接到SERVER(微控制器)并等待接收数据,因此服务器无法将C#程序识别为客户端哈哈。 So what I did was as soon as my C# connects to the microcontroller, it will send first a certain character or string to the server and then it will now starts receiving the data. 因此,我所做的就是C#连接到微控制器后,它将首先向服务器发送特定的字符或字符串,然后它将开始接收数据。 yay!!! 好极了!!!

But one last problem is how to get the values from the richtextbox (since I put/add all the received string in to this rtb) and then put them in the 5 labels. 但是最后一个问题是如何从richtextbox中获取值(因为我将所有接收到的字符串放入/添加到此rtb中),然后将其放入5个标签中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM