none
建立Socket並收封包show在Form上 RRS feed

  • 問題

  • 主要的想法是開啟一各視窗..但有封包近來時就將他Show在Form的textBox中

    目前做法開一各Form當執行時在Form_Load開啟PORT

    但不知道在哪各事件中建立Socket並隨時在背景可以接收封包

    目前在Form_Load中執行....但這樣的程式碼會導致我的Form根本開不起來

    請各位高手可以給我一點建議嗎??

     

     private void Form1_Load(object sender, EventArgs e)
     {
                /*catch Host IP*/
                string HostName = Dns.GetHostName();
                IPHostEntry HostEntry = Dns.GetHostEntry(HostName);
                string LocalIP = HostEntry.AddressList[0].ToString();
                IPAddress MyIP = IPAddress.Parse(LocalIP);
                TcpListener server = new TcpListener(MyIP, 6000);
                server.Start();

     

                // Buffer for reading data
                Byte[] bytes = new Byte[1000];
                String data = null;

                // Enter the listening loop.
                while (true)
                {
                    txtInMsg.Text = ("Waiting for a connection... ");

                    // Perform a blocking call to accept requests.
                    // You could also user server.AcceptSocket() here.
                    TcpClient client = server.AcceptTcpClient();
                    txtInMsg.Text = ("Connected!");

                    data = null;

                    // Get a stream object for reading and writing
                    NetworkStream stream = client.GetStream();

                    int i;

                    // Loop to receive all the data sent by the client.
                    while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        // Translate data bytes to a ASCII string.
                        data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                        txtInMsg.Text = "Received:" + bytes;

                        // Process the data sent by the client.
                        data = data.ToUpper();

                        byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);

                        // Send back a response.
                        //stream.Write(msg, 0, msg.Length);
                        txtOutMsg.Text = "Sent: " + data;
                    }

                    // Shutdown and end connection
                    client.Close();
                }
               
            }

     

    2008年7月9日 上午 02:04

解答

所有回覆