Ir para conteúdo

Arquivado

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

Alexandre Carmo

Executar mais de um processo no mesmo sistema

Recommended Posts

Boa tarde
Fiz um código baseado em alguns tutoriais na net e aqui no fórum que faz a leitura de algumas informações enviadas via socket, o programa esta funcionando, a leitura vem de um determinado ip e porta.
Porém é o seguinte o equipamento que me envia os dados ele tem duas portas, logo eu precisava que no mesmo código ele pegue os dados que vem da porta 8081 e 8082 do ip do aparelho, para testar se estava funcionando eu clonei o código no mesmo form coloquei dois listview e mandei executar, funcionou porém na minha opinião ficou muito sujo, deve ter um modo que apenas com um código eu consiga pegar os dados das duas portas e jogar os dados de cada porta em um listview.
Abaixo segue o código, porém para não ficar muita coisa na tela vou postar o código pegando apenas de uma porta:
using ....;
.....

delegate void AddMessage(string sNewMessage);

private Socket m_sock;
        private byte[] m_byBuff = new byte[256];
        private event AddMessage m_AddMessage;  

public Form1()
        {
            InitializeComponent();
           
            m_AddMessage = new AddMessage(OnAddMessage);
        }
private void Form1_Load(object sender, EventArgs e)
        {
            listView1.View = View.Details;
            listView1.Columns.Add("Hexa");
            listView1.Columns[0].Width = 200;
            listView1.Columns.Add("Wigand");
            listView1.Columns[1].Width = 200;
            listView1.View = View.Details;

        }

private void m_btnConnect_Click(object sender, 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 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!");
            }
        }
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)
        {
            string x = sMessage.Replace("\n","");
            if (x.Length == 10)
            {
                string digitos_iniciais = Convert.ToInt64(x.Substring(4, 2), 16).ToString();
                string digitos_finais = Convert.ToInt64(x.Substring(6), 16).ToString();

                ListViewItem lvi = new ListViewItem(sMessage);
                lvi.SubItems.Add(digitos_iniciais + " " + digitos_finais);
                listView1.Items.Add(lvi);
            }
        }
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!");
            }
        }
 private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (m_sock != null && m_sock.Connected)
            {
                m_sock.Shutdown(SocketShutdown.Both);
                m_sock.Close();
            }

        }

 

 

Compartilhar este post


Link para o post
Compartilhar em outros sites

Boa tarde

 

Consegui fazer, segue o exemplo para caso alguém precise, tive ajuda com tutorias e post do fórum da msdn.

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net;									
using System.Net.Sockets;							
using System.Text;

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

namespace Edge50
{
    public partial class Form1 : Form
    {

        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

        private Socket m_sock2;						// Server connection
       // private byte[] m_byBuff2 = new byte[256];	// Recieved data buffer
       // private event AddMessage m_AddMessage2;				// Add Message Event handler for Form

        public Form1()
        {
            InitializeComponent();
            // Add Message Event handler for Form decoupling from input thread
            m_AddMessage = new AddMessage(OnAddMessage);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            listView1.View = View.Details;
            listView1.Columns.Add("Hexa");
            listView1.Columns[0].Width = 200;
            listView1.Columns.Add("Wigand");
            listView1.Columns[1].Width = 200;
            listView1.View = View.Details;

            listView2.View = View.Details;
            listView2.Columns.Add("Hexa");
            listView2.Columns[0].Width = 200;
            listView2.Columns.Add("Wigand");
            listView2.Columns[1].Width = 200;
            listView2.View = View.Details;
        }

        private void m_btnConnect_Click(object sender, 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();
                }
                ///////////////////////////////////////////////////
                // clone o if para o sock2 ou faça uma lista e um for.
                ////////////////////////////////////////////////////


                // Create the socket object
                m_sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                m_sock2 = 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));
                IPEndPoint epServer2 = new IPEndPoint(IPAddress.Parse(m_tbServerAddress.Text), Convert.ToInt32(lblPorta2.Text));

                // Connect to server non-Blocking method
                m_sock.Blocking = false;
                m_sock2.Blocking = false;

                AsyncCallback onconnect = new AsyncCallback(OnConnect);
                m_sock.BeginConnect(epServer, onconnect, m_sock);
                m_sock2.BeginConnect(epServer2, onconnect, m_sock2);

            }
            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;
        //    sock.RemoteEndPoint.
         // MessageBox.Show(IPAddress.Parse(((IPEndPoint)sock.RemoteEndPoint).Address.ToString()) + "on port number " + ((IPEndPoint)sock.RemoteEndPoint).Port.ToString());


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

        public void OnRecievedData(IAsyncResult ar)
        {
            // Socket was the passed in object
            Socket sock = (Socket)ar.AsyncState;
            //MessageBox.Show(IPAddress.Parse(((IPEndPoint)sock.RemoteEndPoint).Address.ToString()) + "on port number " + ((IPEndPoint)sock.RemoteEndPoint).Port.ToString());

            // 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);
                    string[] sRecieved = new string[] { Encoding.ASCII.GetString(m_byBuff, 0, nBytesRec),  ((IPEndPoint)sock.RemoteEndPoint).Port.ToString() };
                    
                    // WARNING : The following line is NOT thread safe. Invoke is
                    // m_lbRecievedData.Items.Add( sRecieved );
                    Invoke(m_AddMessage, new object[] { 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(ex.Message, "erro!");
            }
        }

       

        public void OnAddMessage(string[] sMessage)
        {

            //MessageBox.Show(sMessage[0] + " " + sMessage[1] );

            string x = sMessage[0].Replace("\n", "");
            if (x.Length == 10)
            {
                string digitos_iniciais = Convert.ToInt64(x.Substring(4, 2), 16).ToString();
                string digitos_finais = Convert.ToInt64(x.Substring(6), 16).ToString();

                if (sMessage[1] == "8081")
                {
                    ListViewItem lvi = new ListViewItem(x);
                    lvi.SubItems.Add(digitos_iniciais + " " + digitos_finais);
                    listView1.Items.Add(lvi);
                }
                else
                {
                    ListViewItem lvi2 = new ListViewItem(x);
                    lvi2.SubItems.Add(digitos_iniciais + " " + digitos_finais);
                    listView2.Items.Add(lvi2);
                }
            }
        }

       

        /// <summary>
        /// Setup the callback for recieved data and loss of conneciton
        /// </summary>
        public void SetupRecieveCallback(Socket sock)
        {
        //    MessageBox.Show(IPAddress.Parse(((IPEndPoint)sock.RemoteEndPoint).Address.ToString()) + "on port number " + ((IPEndPoint)sock.RemoteEndPoint).Port.ToString());
            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!");
            }
        }

       

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (m_sock != null && m_sock.Connected)
            {
                m_sock.Shutdown(SocketShutdown.Both);
                m_sock.Close();
            }

            if (m_sock2 != null && m_sock2.Connected)
            {
                m_sock2.Shutdown(SocketShutdown.Both);
                m_sock2.Close();
            }
        }
    }
}

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.