Ir para conteúdo

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Alexandre Carmo

Problemas com sockets

Recommended Posts

Boa tarde

Pessoal tenho um hardware ip que fica mandando informações via socket, consegui conectar o hardware e capturar as informações(C# desktop), porém o problema é que na hora de exibir a informação na tela ele me exibe a mesma informação repetidas vezes na mesma linha, a informação vem repetida mesmo porém tem que vir quebrando linha, por exemplo a informação enviada é:

3DAC3006

Estou jogando essa informação no listview, logo deveria me exibir assim:

3DAC3006

3DAC3006

3DAC3006

...

 

Porém esta me exibindo assim:

3DAC30063DAC30063DAC30063DAC3006

3DAC30063DAC30063DAC30063DAC3006

3DAC30063DAC30063DAC30063DAC3006

...

Porque isso?

Abaixo segue o código:

private void exibeStatus(string status)
        {
            listView1.Items.Add(status); 
        }

        private delegate void AddItemsDelegate(string newItem);

        public void RunClient()
        {
            try
            {
                while (true) 
                {
                    tcpClient = new TcpClient();
                    tcpClient.Connect("192.168.1.50", 8081);

                    networkStream = tcpClient.GetStream();
                    // byte[] buffer = new byte[32];
                    // MessageBox.Show(networkStream.Read(buffer, 0, 11).ToString() );  


                    binaryReader = new BinaryReader(networkStream);


                    try
                    {
                        message = binaryReader.ReadString();


                        this.Invoke(new AddItemsDelegate(exibeStatus), message);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Erro");
                    }

                     binaryReader.Close();

                    networkStream.Close();
                    tcpClient.Close();
                    message = "";
                } 

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Erro");
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

            listView1.View = View.Details;
            listView1.Columns.Add("Tags");
            listView1.Columns[0].Width = 500;

            thread = new Thread(RunClient);
            thread.Start();

            
        }

Como corrijo esse problema? Sei que esta relaciona a essa linha:

message = binaryReader.ReadString();

Mas não consigo resolver, alguém tem ideia?

Compartilhar este post


Link para o post
Compartilhar em outros sites

Boa tarde KhaosDoctor

 

Obrigado pela ajuda, porém não entendi o que vocÊ me esta informando onde estou adicionando as colunas, seria no listview ? Por exemplo para testar retirei o listview e mandei adicionar direto no textbox e o resultador foi o mesmo. Ou não entendi direito o que você informou?

Compartilhar este post


Link para o post
Compartilhar em outros sites

Boa tarde

 

Na verdade por enquanto estou apenas querendo exibir o valor que estou recebendo via socket no form, então estou exibindo em um lisview, mas pode ser em qualquer outro objeto. Porém pesquisando, notei que o o valor que estou recebendo via socket é um tipo de listener, então acredito que tenho que trabalhar com socket usando listener, achei algumas coisas na internet e estou pesquisando.

Para vocÊ ter um ideia o hardware que é uma antena ip que via socket fica me mandando uma string preciso pegar cada string enviada e exibir na tela.

O que vocÊ acha?

Compartilhar este post


Link para o post
Compartilhar em outros sites

Cara achei uns tutorias na msdn de listerner para socket e consegui fazer, abaixo segue o código de exemplo:

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 Label label1;
        private Label label2;
        private TextBox lblPorta;
		/// <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_btnConnect = new System.Windows.Forms.Button();
            this.m_lbRecievedData = new System.Windows.Forms.ListBox();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.lblPorta = new System.Windows.Forms.TextBox();
            this.SuspendLayout();
            // 
            // m_tbServerAddress
            // 
            this.m_tbServerAddress.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
            | System.Windows.Forms.AnchorStyles.Right)));
            this.m_tbServerAddress.Location = new System.Drawing.Point(38, 5);
            this.m_tbServerAddress.Name = "m_tbServerAddress";
            this.m_tbServerAddress.Size = new System.Drawing.Size(103, 20);
            this.m_tbServerAddress.TabIndex = 1;
            this.m_tbServerAddress.Text = "192.168.1.50";
            // 
            // m_btnConnect
            // 
            this.m_btnConnect.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.m_btnConnect.Location = new System.Drawing.Point(366, 8);
            this.m_btnConnect.Name = "m_btnConnect";
            this.m_btnConnect.Size = new System.Drawing.Size(75, 23);
            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)((((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(449, 220);
            this.m_lbRecievedData.TabIndex = 2;
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(12, 8);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(20, 13);
            this.label1.TabIndex = 3;
            this.label1.Text = "IP:";
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(148, 9);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(35, 13);
            this.label2.TabIndex = 5;
            this.label2.Text = "Porta:";
            // 
            // lblPorta
            // 
            this.lblPorta.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
            | System.Windows.Forms.AnchorStyles.Right)));
            this.lblPorta.Location = new System.Drawing.Point(189, 6);
            this.lblPorta.Name = "lblPorta";
            this.lblPorta.Size = new System.Drawing.Size(103, 20);
            this.lblPorta.TabIndex = 4;
            this.lblPorta.Text = "8081";
            // 
            // FormMain
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(450, 287);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.lblPorta);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.m_lbRecievedData);
            this.Controls.Add(this.m_tbServerAddress);
            this.Controls.Add(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.Load += new System.EventHandler(this.FormMain_Load);
            this.ResumeLayout(false);
            this.PerformLayout();

		}
		#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 ), Convert.ToInt32(lblPorta.Text)   );

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

        private void FormMain_Load(object sender, EventArgs e)
        {

        }
	}
}

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.