Модераторы: gambit
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Клиент-сервер вывод инфы в Textbox 
V
    Опции темы
Barabeo
Дата 23.5.2011, 21:25 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Бывалый
*


Профиль
Группа: Участник
Сообщений: 234
Регистрация: 2.10.2010

Репутация: нет
Всего: нет



Клиент должен вывести в TextBox Arp-кэш.И далее содержимое TextBoxa нужно будет отправить серверу.
Куда нужно вставить ф-цию определения кэша?

Вот код он не пашет.
Код

using System;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
//using System.Linq;
using System.Text;
using System.Runtime.InteropServices;


namespace DefaultNamespace
{
    /// <summary>
    /// Description of SocketClient.    
    /// </summary>
    public class SocketClient : System.Windows.Forms.Form
    {
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Button buttonDisconnect;
        private System.Windows.Forms.TextBox textBoxIP;
        private System.Windows.Forms.Label label5;
        private System.Windows.Forms.Button buttonConnect;
        private System.Windows.Forms.TextBox textBoxPort;
        private System.Windows.Forms.RichTextBox richTextRxMessage;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.TextBox textBoxConnectStatus;
        private System.Windows.Forms.RichTextBox richTextTxMessage;
        private System.Windows.Forms.Button buttonSendMessage;
        private System.Windows.Forms.Button buttonClose;

        const int MAXLEN_PHYSADDR = 8;
        const int ERROR_INSUFFICIENT_BUFFER = 122;

        [DllImport("IpHlpApi.dll")]
        [return: MarshalAs(UnmanagedType.U4)]
        static extern int GetIpNetTable(IntPtr pIpNetTable,
                                        [MarshalAs(UnmanagedType.U4)] 
                                      ref int pdwSize,
                                        bool bOrder);

        [StructLayout(LayoutKind.Sequential)]
        struct MIB_IPNETROW
        {
            [MarshalAs(UnmanagedType.U4)]
            public int dwIndex;
            [MarshalAs(UnmanagedType.U4)]
            public int dwPhysAddrLen;
            [MarshalAs(UnmanagedType.U1)]
            public byte mac0;
            [MarshalAs(UnmanagedType.U1)]
            public byte mac1;
            [MarshalAs(UnmanagedType.U1)]
            public byte mac2;
            [MarshalAs(UnmanagedType.U1)]
            public byte mac3;
            [MarshalAs(UnmanagedType.U1)]
            public byte mac4;
            [MarshalAs(UnmanagedType.U1)]
            public byte mac5;
            [MarshalAs(UnmanagedType.U1)]
            public byte mac6;
            [MarshalAs(UnmanagedType.U1)]
            public byte mac7;
            [MarshalAs(UnmanagedType.U4)]
            public int dwAddr;
            [MarshalAs(UnmanagedType.U4)]
            public int dwType;
        } 

        byte[] m_dataBuffer = new byte [40000];
        IAsyncResult m_result;
        public AsyncCallback m_pfnCallBack ;
        public Socket m_clientSocket;
        
        public SocketClient()
        {
            //
            // The InitializeComponent() call is required for Windows Forms designer support.
            //
            InitializeComponent();
            
            textBoxIP.Text = GetIP();


              //ВОТ ЭТОТ КУСОК КОДА
             int bytesNeeded = 0;
             // The result from the API call. 
             int result = GetIpNetTable(IntPtr.Zero, ref bytesNeeded, false);
             // Call the function, expecting an insufficient buffer. 
             if (result != ERROR_INSUFFICIENT_BUFFER)
             {
                 // Throw an exception. 
                 throw new Win32Exception(result);
             }
             // Allocate the memory, do it in a try/finally block, to ensure 
             // that it is released. 
             IntPtr buffer = IntPtr.Zero;
             // Try/finally. 
             try
             {
                 // Allocate the memory. 
                 buffer = Marshal.AllocCoTaskMem(bytesNeeded);
                 // Make the call again. If it did not succeed, then 
                 // raise an error. 
                 result = GetIpNetTable(buffer, ref bytesNeeded, false);
                 // If the result is not 0 (no error), then throw an exception. 
                 if (result != 0)
                 {
                     // Throw an exception. 
                     throw new Win32Exception(result);
                 }
                 // Now we have the buffer, we have to marshal it. We can read 
                 // the first 4 bytes to get the length of the buffer. 
                 int entries = Marshal.ReadInt32(buffer);
                 // Increment the memory pointer by the size of the int. 
                 IntPtr currentBuffer = new IntPtr(buffer.ToInt64() +
                                                   Marshal.SizeOf(typeof (int)));
                 // Allocate an array of entries. 
                 MIB_IPNETROW[] table = new MIB_IPNETROW[entries];
                 // Cycle through the entries. 
                 for (int index = 0; index < entries; index++)
                 {
                     // Call PtrToStructure, getting the structure information. 
                     table[index] = (MIB_IPNETROW) Marshal.PtrToStructure(new
                                                                              IntPtr(currentBuffer.ToInt64() + (index*
                                                                                                                Marshal.
                                                                                                                    SizeOf
                                                                                                                    (typeof
                                                                                                                         (                                                                                                        MIB_IPNETROW
                                                                                                                         )))),
                                                                          typeof (MIB_IPNETROW));
                 }
                 for (int index = 0; index < entries; index++)
                 {
                     IPAddress ip = new IPAddress(table[index].dwAddr);

                     string mac = "";
                     mac = "IP:" + ip.ToString() + "\tMAC:";

                     byte b;
                     b = table[index].mac0;

                     if (b < 0x10)
                     {
                         mac += "0";
                       
                     }
                     else
                     {
                         mac += "";
              
                     }
                     richTextTxMessage(b.ToString("X"));
                     b = table[index].mac1;

                     if (b < 0x10)
                     {
                         mac += "-0";
                       
                     }
                     else
                     {
                         mac += "-";
                       
                     }
                     mac += b.ToString("X");
                    
                     b = table[index].mac2;
                     if (b < 0x10)
                     {
                         mac += "-0";
                        
                     }
                     else
                     {
                         mac += "-";
                       
                     }
                     mac += b.ToString("X");
                   
                     b = table[index].mac3;
                     if (b < 0x10)
                     {
                         mac += "-0";
                        
                     }
                     else
                     {
                         mac += "-";
                        
                     }
                     mac += b.ToString("X");
                    
                     b = table[index].mac4;
                     if (b < 0x10)
                     {
                         mac += "-0";
                       
                     }
                     else
                     {
                         mac += "-";
                       
                     }
                     mac += b.ToString("X");
                    
                     b = table[index].mac5;
                     if (b < 0x10)
                     {
                         mac += "-0";
                        
                     }
                     else
                     {
                         mac += "-";
                       
                     }
                     mac += b.ToString("X");
                    
                     richTextTxMessage(mac);
                 }
             }
             finally
             {
                 // Release the memory. 
                 Marshal.FreeCoTaskMem(buffer);
             }
         }//И ДО СЕДОВА




        }
        
        [STAThread]
        public static void Main(string[] args)
        {
            Application.Run(new SocketClient());

        }
        
        void ButtonCloseClick(object sender, System.EventArgs e)
        {
            if ( m_clientSocket != null )
            {
                m_clientSocket.Close ();
                m_clientSocket = null;
            }        
            Close();
        }
        
        void ButtonConnectClick(object sender, System.EventArgs e)
        {
            // See if we have text on the IP and Port text fields
            if(textBoxIP.Text == "" || textBoxPort.Text == ""){
                MessageBox.Show("IP Address and Port Number are required to connect to the Server\n");
                return;
            }
            try
            {
                UpdateControls(false);
                // Create the socket instance
                m_clientSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
                
                // Cet the remote IP address
                IPAddress ip = IPAddress.Parse (textBoxIP.Text);
                int iPortNo = System.Convert.ToInt16 ( textBoxPort.Text);
                // Create the end point 
                IPEndPoint ipEnd = new IPEndPoint (ip,iPortNo);
                // Connect to the remote host
                m_clientSocket.Connect ( ipEnd );
                if(m_clientSocket.Connected) {
                    
                    UpdateControls(true);
                    //Wait for data asynchronously 
                    WaitForData();
                    
                }
            }
            catch(SocketException se)
            {
                string str;
                str = "\nConnection failed, is the server running?\n" + se.Message;
                MessageBox.Show (str);
                UpdateControls(false);
            }        
        }            
        void ButtonSendMessageClick(object sender, System.EventArgs e)
        {
            try
            {
                Object objData = richTextTxMessage.Text;
                byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString ());
                if(m_clientSocket != null){
                    m_clientSocket.Send (byData);
                }
            }
            catch(SocketException se)
            {
                MessageBox.Show (se.Message );
            }    
        }
        public void WaitForData()
        {
            try
            {
                if  ( m_pfnCallBack == null ) 
                {
                    m_pfnCallBack = new AsyncCallback (OnDataReceived);
                }
                SocketPacket theSocPkt = new SocketPacket ();
                theSocPkt.thisSocket = m_clientSocket;
                // Start listening to the data asynchronously
                m_result = m_clientSocket.BeginReceive (theSocPkt.dataBuffer,
                                                        0, theSocPkt.dataBuffer.Length,
                                                        SocketFlags.None, 
                                                        m_pfnCallBack, 
                                                        theSocPkt);
            }
            catch(SocketException se)
            {
                MessageBox.Show (se.Message );
            }

        }
        public class SocketPacket
        {
            public System.Net.Sockets.Socket thisSocket;
            public byte[] dataBuffer = new byte[1];
        }

        public  void OnDataReceived(IAsyncResult asyn)
        {
            try
            {
                SocketPacket theSockId = (SocketPacket)asyn.AsyncState ;
                int iRx  = theSockId.thisSocket.EndReceive (asyn);
                char[] chars = new char[iRx +  1];
                System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
                int charLen = d.GetChars(theSockId.dataBuffer, 0, iRx, chars, 0);
                System.String szData = new System.String(chars);
                richTextRxMessage.Text = richTextRxMessage.Text + szData;
                StreamWriter tt = new StreamWriter("out.txt", true);
                tt.Write(szData);
                tt.Close();
                WaitForData();
            }
            catch (ObjectDisposedException )
            {
                System.Diagnostics.Debugger.Log(0,"1","\nOnDataReceived: Socket has been closed\n");
            }
            catch(SocketException se)
            {
                MessageBox.Show (se.Message );
            }
        }    
        private void UpdateControls( bool connected ) 
        {
            buttonConnect.Enabled = !connected;
            buttonDisconnect.Enabled = connected;
            string connectStatus = connected? "Connected" : "Not Connected";
            textBoxConnectStatus.Text = connectStatus;
        }
        void ButtonDisconnectClick(object sender, System.EventArgs e)
        {
            if ( m_clientSocket != null )
            {
                m_clientSocket.Close();
                m_clientSocket = null;
                UpdateControls(false);
            }
        }
       //----------------------------------------------------    
       // This is a helper function used (for convenience) to 
       // get the IP address of the local machine
       //----------------------------------------------------
       String GetIP()
       {       
            String strHostName = Dns.GetHostName();
        
            // Find host by name
            IPHostEntry iphostentry = Dns.GetHostByName(strHostName);
        
            // Grab the first IP addresses
            String IPStr = "";
            foreach(IPAddress ipaddress in iphostentry.AddressList){
                IPStr = ipaddress.ToString();
                return IPStr;
            }
            return IPStr;
       }

        private void SocketClient_Load(object sender, System.EventArgs e)
        {
        
        }        
    }
}



PM MAIL   Вверх
Barabeo
Дата 23.5.2011, 22:27 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Бывалый
*


Профиль
Группа: Участник
Сообщений: 234
Регистрация: 2.10.2010

Репутация: нет
Всего: нет



Вот сделал.

Код

namespace DefaultNamespace
{
    /// <summary>
    /// Description of SocketClient.    
    /// </summary>
    public class SocketClient : System.Windows.Forms.Form
    {
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Button buttonDisconnect;
        private System.Windows.Forms.TextBox textBoxIP;
        private System.Windows.Forms.Label label5;
        private System.Windows.Forms.Button buttonConnect;
        private System.Windows.Forms.TextBox textBoxPort;
        private System.Windows.Forms.RichTextBox richTextRxMessage;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.TextBox textBoxConnectStatus;
        private System.Windows.Forms.RichTextBox richTextTxMessage;
        private System.Windows.Forms.Button buttonSendMessage;
        private System.Windows.Forms.Button buttonClose;

        const int MAXLEN_PHYSADDR = 8;
        private Button GetARP;
        const int ERROR_INSUFFICIENT_BUFFER = 122;

        [DllImport("IpHlpApi.dll")]
        [return: MarshalAs(UnmanagedType.U4)]
        static extern int GetIpNetTable(IntPtr pIpNetTable,
                                        [MarshalAs(UnmanagedType.U4)] 
                                      ref int pdwSize,
                                        bool bOrder);

        [StructLayout(LayoutKind.Sequential)]
        struct MIB_IPNETROW
        {
            [MarshalAs(UnmanagedType.U4)]
            public int dwIndex;
            [MarshalAs(UnmanagedType.U4)]
            public int dwPhysAddrLen;
            [MarshalAs(UnmanagedType.U1)]
            public byte mac0;
            [MarshalAs(UnmanagedType.U1)]
            public byte mac1;
            [MarshalAs(UnmanagedType.U1)]
            public byte mac2;
            [MarshalAs(UnmanagedType.U1)]
            public byte mac3;
            [MarshalAs(UnmanagedType.U1)]
            public byte mac4;
            [MarshalAs(UnmanagedType.U1)]
            public byte mac5;
            [MarshalAs(UnmanagedType.U1)]
            public byte mac6;
            [MarshalAs(UnmanagedType.U1)]
            public byte mac7;
            [MarshalAs(UnmanagedType.U4)]
            public int dwAddr;
            [MarshalAs(UnmanagedType.U4)]
            public int dwType;
        } 

        byte[] m_dataBuffer = new byte [40000];
        IAsyncResult m_result;
        public AsyncCallback m_pfnCallBack ;
        public Socket m_clientSocket;
        
        public SocketClient()
        {
            //
            // The InitializeComponent() call is required for Windows Forms designer support.
            //
            InitializeComponent();
            
            textBoxIP.Text = GetIP();

        }
        
        [STAThread]
        public static void Main(string[] args)
        {
            Application.Run(new SocketClient());

        }
        
        void ButtonCloseClick(object sender, System.EventArgs e)
        {
            if ( m_clientSocket != null )
            {
                m_clientSocket.Close ();
                m_clientSocket = null;
            }        
            Close();
        }
        
        void ButtonConnectClick(object sender, System.EventArgs e)
        {
            // See if we have text on the IP and Port text fields
            if(textBoxIP.Text == "" || textBoxPort.Text == ""){
                MessageBox.Show("IP Address and Port Number are required to connect to the Server\n");
                return;
            }
            try
            {
                UpdateControls(false);
                // Create the socket instance
                m_clientSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
                
                // Cet the remote IP address
                IPAddress ip = IPAddress.Parse (textBoxIP.Text);
                int iPortNo = System.Convert.ToInt16 ( textBoxPort.Text);
                // Create the end point 
                IPEndPoint ipEnd = new IPEndPoint (ip,iPortNo);
                // Connect to the remote host
                m_clientSocket.Connect ( ipEnd );
                if(m_clientSocket.Connected) {
                    
                    UpdateControls(true);
                    //Wait for data asynchronously 
                    WaitForData();
                    
                }
            }
            catch(SocketException se)
            {
                string str;
                str = "\nConnection failed, is the server running?\n" + se.Message;
                MessageBox.Show (str);
                UpdateControls(false);
            }        
        }            
        void ButtonSendMessageClick(object sender, System.EventArgs e)
        {
            try
            {
                Object objData = richTextTxMessage.Text;
                byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString ());
                if(m_clientSocket != null){
                    m_clientSocket.Send (byData);
                }
            }
            catch(SocketException se)
            {
                MessageBox.Show (se.Message );
            }    
        }
        public void WaitForData()
        {
            try
            {
                if  ( m_pfnCallBack == null ) 
                {
                    m_pfnCallBack = new AsyncCallback (OnDataReceived);
                }
                SocketPacket theSocPkt = new SocketPacket ();
                theSocPkt.thisSocket = m_clientSocket;
                // Start listening to the data asynchronously
                m_result = m_clientSocket.BeginReceive (theSocPkt.dataBuffer,
                                                        0, theSocPkt.dataBuffer.Length,
                                                        SocketFlags.None, 
                                                        m_pfnCallBack, 
                                                        theSocPkt);
            }
            catch(SocketException se)
            {
                MessageBox.Show (se.Message );
            }

        }
        public class SocketPacket
        {
            public System.Net.Sockets.Socket thisSocket;
            public byte[] dataBuffer = new byte[1];
        }

        public  void OnDataReceived(IAsyncResult asyn)
        {
            try
            {
                SocketPacket theSockId = (SocketPacket)asyn.AsyncState ;
                int iRx  = theSockId.thisSocket.EndReceive (asyn);
                char[] chars = new char[iRx +  1];
                System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
                int charLen = d.GetChars(theSockId.dataBuffer, 0, iRx, chars, 0);
                System.String szData = new System.String(chars);
                richTextRxMessage.Text = richTextRxMessage.Text + szData;
                StreamWriter tt = new StreamWriter("out.txt", true);
                tt.Write(szData);
                tt.Close();
                WaitForData();
            }
            catch (ObjectDisposedException )
            {
                System.Diagnostics.Debugger.Log(0,"1","\nOnDataReceived: Socket has been closed\n");
            }
            catch(SocketException se)
            {
                MessageBox.Show (se.Message );
            }
        }    
        private void UpdateControls( bool connected ) 
        {
            buttonConnect.Enabled = !connected;
            buttonDisconnect.Enabled = connected;
            string connectStatus = connected? "Connected" : "Not Connected";
            textBoxConnectStatus.Text = connectStatus;
        }
        void ButtonDisconnectClick(object sender, System.EventArgs e)
        {
            if ( m_clientSocket != null )
            {
                m_clientSocket.Close();
                m_clientSocket = null;
                UpdateControls(false);
            }
        }
       //----------------------------------------------------    
       // This is a helper function used (for convenience) to 
       // get the IP address of the local machine
       //----------------------------------------------------
       String GetIP()
       {       
            String strHostName = Dns.GetHostName();
        
            // Find host by name
            IPHostEntry iphostentry = Dns.GetHostByName(strHostName);
        
            // Grab the first IP addresses
            String IPStr = "";
            foreach(IPAddress ipaddress in iphostentry.AddressList){
                IPStr = ipaddress.ToString();
                return IPStr;
            }
            return IPStr;
       }

        private void SocketClient_Load(object sender, System.EventArgs e)
        {
        
        }

        private void GetARP_Click(object sender, EventArgs e)
        {
            int bytesNeeded = 0;
             // The result from the API call. 
             int result = GetIpNetTable(IntPtr.Zero, ref bytesNeeded, false);
             // Call the function, expecting an insufficient buffer. 
             if (result != ERROR_INSUFFICIENT_BUFFER)
             {
                 // Throw an exception. 
                 throw new Win32Exception(result);
             }
             // Allocate the memory, do it in a try/finally block, to ensure 
             // that it is released. 
             IntPtr buffer = IntPtr.Zero;
             // Try/finally. 
             try
             {
                 // Allocate the memory. 
                 buffer = Marshal.AllocCoTaskMem(bytesNeeded);
                 // Make the call again. If it did not succeed, then 
                 // raise an error. 
                 result = GetIpNetTable(buffer, ref bytesNeeded, false);
                 // If the result is not 0 (no error), then throw an exception. 
                 if (result != 0)
                 {
                     // Throw an exception. 
                     throw new Win32Exception(result);
                 }
                 // Now we have the buffer, we have to marshal it. We can read 
                 // the first 4 bytes to get the length of the buffer. 
                 int entries = Marshal.ReadInt32(buffer);
                 // Increment the memory pointer by the size of the int. 
                 IntPtr currentBuffer = new IntPtr(buffer.ToInt64() +
                                                   Marshal.SizeOf(typeof (int)));
                 // Allocate an array of entries. 
                 MIB_IPNETROW[] table = new MIB_IPNETROW[entries];
                 // Cycle through the entries. 
                 for (int index = 0; index < entries; index++)
                 {
                     // Call PtrToStructure, getting the structure information. 
                     table[index] = (MIB_IPNETROW) Marshal.PtrToStructure(new
                                                                              IntPtr(currentBuffer.ToInt64() + (index*
                                                                                                                Marshal.
                                                                                                                    SizeOf
                                                                                                                    (typeof
                                                                                                                         (                                                                                                        MIB_IPNETROW
                                                                                                                         )))),
                                                                          typeof (MIB_IPNETROW));
                 }
                 for (int index = 0; index < entries; index++)
                 {
                     IPAddress ip = new IPAddress(table[index].dwAddr);

                     string mac = "";
                     mac = "IP:" + ip.ToString() + "\tMAC:";

                     byte b;
                     b = table[index].mac0;

                     if (b < 0x10)
                     {
                         mac += "0";
                       
                     }
                     else
                     {
                         mac += "";
              
                     }
                     richTextTxMessage.Text = richTextTxMessage.Text + b.ToString("X");
                     b = table[index].mac1;

                     if (b < 0x10)
                     {
                         mac += "-0";
                       
                     }
                     else
                     {
                         mac += "-";
                       
                     }
                     mac += b.ToString("X");
                    
                     b = table[index].mac2;
                     if (b < 0x10)
                     {
                         mac += "-0";
                        
                     }
                     else
                     {
                         mac += "-";
                       
                     }
                     mac += b.ToString("X");
                   
                     b = table[index].mac3;
                     if (b < 0x10)
                     {
                         mac += "-0";
                        
                     }
                     else
                     {
                         mac += "-";
                        
                     }
                     mac += b.ToString("X");
                    
                     b = table[index].mac4;
                     if (b < 0x10)
                     {
                         mac += "-0";
                       
                     }
                     else
                     {
                         mac += "-";
                       
                     }
                     mac += b.ToString("X");
                    
                     b = table[index].mac5;
                     if (b < 0x10)
                     {
                         mac += "-0";
                        
                     }
                     else
                     {
                         mac += "-";
                       
                     }
                     mac += b.ToString("X");

                     richTextTxMessage.Text = richTextTxMessage.Text + (mac);
                 }
             }
             finally
             {
                 // Release the memory. 
                 Marshal.FreeCoTaskMem(buffer);
             }
         }//button

        }        
    }


Теперь клиент выводит инфу, но когда пытаюсь её отправить на сервер вылетает вот это:

There is no source code available for the current location.

Почему не отправляется содержимое RichTextBox'a?
PM MAIL   Вверх
Barabeo
Дата 23.5.2011, 22:49 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Бывалый
*


Профиль
Группа: Участник
Сообщений: 234
Регистрация: 2.10.2010

Репутация: нет
Всего: нет



И ещё такой вопрос - Как сделать чтобы сервер сам считывал данные из текст бокса?
Т.е. когда я на клиенте нажал кнопку получить ARP, сервер сам считал содержимое бокса (т.е. уже не нужно нажимать кнопку SendMessage) ?
PM MAIL   Вверх
Экскалупатор
Дата 23.5.2011, 23:48 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
***


Профиль
Группа: Завсегдатай
Сообщений: 1746
Регистрация: 1.4.2009
Где: г. Минск

Репутация: нет
Всего: 24



а как сервер узнает что ты нажал кнопку? ему надо это сообщить, так уже проще ему сразу сообщить что ты там ввел. если уж очень надо то реализуй метод на клиенте который будет возвращать содержимое текстбокса а сервер пусть этот метод дергает периодически.
PM MAIL ICQ   Вверх
Barabeo
Дата 24.5.2011, 21:42 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Бывалый
*


Профиль
Группа: Участник
Сообщений: 234
Регистрация: 2.10.2010

Репутация: нет
Всего: нет



Цитата(Экскалупатор @ 23.5.2011,  23:48)
а как сервер узнает что ты нажал кнопку? ему надо это сообщить, так уже проще ему сразу сообщить что ты там ввел. если уж очень надо то реализуй метод на клиенте который будет возвращать содержимое текстбокса а сервер пусть этот метод дергает периодически.

Если не трудно, можешь накидать, "дергалку сервера"?

PM MAIL   Вверх
Экскалупатор
Дата 25.5.2011, 00:00 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
***


Профиль
Группа: Завсегдатай
Сообщений: 1746
Регистрация: 1.4.2009
Где: г. Минск

Репутация: нет
Всего: 24



а как у тебя происходит общение между сервером и клиентом? да и я уверен что лучше сделать в обратную сторону, так проще и логичнее, вот представь себе ситуацию что я открою прогу, начну писать что то, а потом пойду курить и кофе пить, а сервер в это время будет с упорством маньяка долбить клиент... да и вообще это как то по не русски... напиши просто отправку данных по нажатию на кнопку, это упростит все.
PM MAIL ICQ   Вверх
-Mikle-
Дата 25.5.2011, 06:37 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Невидимка Vingrad'а
***


Профиль
Группа: Экс. модератор
Сообщений: 1672
Регистрация: 22.6.2003
Где: Казахстан, Астана

Репутация: 1
Всего: 59



Все верно. В правильной архитектуре, инициатором сетевого действия должен быть клиент. Проблема становится очевидна, когда к твоему серверу подключатся 10-15 миллионов клиентов. Представь себе, что сервер будет инициатором в такой ситуации.


--------------------
Если тебе плюют в спину, значит ты впереди...
PM   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Прежде чем создать тему, посмотрите сюда:
cully
mr.DUDA
Exception

Используйте теги [code=csharp][/code] для подсветки кода. Используйтe чекбокс "транслит" если у Вас нет русских шрифтов.

Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, cully, mr.DUDA, Exception.

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Распределённые приложения и сеть | Следующая тема »


 




[ Время генерации скрипта: 0.1047 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.