簡體   English   中英

Windows窗體中的套接字問題。 更改選項卡控件時,套接字停止回復

[英]Socket issue in windows form. Socket stop replying when change tab control

我做了一些程序,啟動一個處理所有客戶端請求的異步套接字。

套接字在調用Form1之前啟動,並且工作正常

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        AsynchronousServer ascSv = new AsynchronousServer();
        Application.Run(new Form1());
        if (ascSv != null)
            ascSv.Stop();
    }
}

--Edited ---(添加了AsynchronousServer.cs)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Server
{
    public class StateObject
    {
        // Client  socket.  
        public Socket workSocket = null;
        // Size of receive buffer.  
        public const int BufferSize = 1024;
        // Receive buffer.  
        public byte[] buffer = new byte[BufferSize];
        // Received data string.  
        public StringBuilder sb = new StringBuilder();
    }

    public class AsynchronousServer
    {
        public ManualResetEvent allDone = new ManualResetEvent(false);
        Socket listener;
        public Thread t;
        public AsynchronousServer()
        {
            t = new Thread(StartListening);
            t.Start();
        }

        public void Stop()
        {
            try
            {
                listener.Shutdown(SocketShutdown.Both);
                listener.Disconnect(false);
                try
                {
                    listener.Close();
                    listener.Dispose();
                }
                catch { }
            }
            catch
            {

            }
            if (t!=null &&t.IsAlive)
            {
                t.Abort();
                t = null;
            }
            listener = null;
        }

        public void StartListening()
        {
            // Establish the local endpoint for the socket.  
            // The DNS name of the computer  
            IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("192.168.100.115"), 11000);

            // Create a TCP/IP socket.  
            listener = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream, ProtocolType.Tcp);

            // Bind the socket to the local endpoint and listen for incoming connections.  
            try
            {
                listener.Bind(localEndPoint);
                listener.Listen(100);

                while (true)
                {
                    // Set the event to nonsignaled state.  
                    allDone.Reset();

                    // Start an asynchronous socket to listen for connections.  
                    //Console.WriteLine("Waiting for a connection...");
                    listener.BeginAccept(
                        new AsyncCallback(AcceptCallback),
                        listener);

                    // Wait until a connection is made before continuing.  
                    allDone.WaitOne();
                }

            }
            catch
            {
                //MessageBox.Show(e.Message);
            }
        }

        public void AcceptCallback(IAsyncResult ar)
        {
            try
            {
                // Signal the main thread to continue.  
                allDone.Set();

                // Get the socket that handles the client request.  
                Socket listener = (Socket)ar.AsyncState;
                Socket handler = listener.EndAccept(ar);

                // Create the state object.  
                StateObject state = new StateObject();
                state.workSocket = handler;
                handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                    new AsyncCallback(ReadCallback), state);
            }
            catch
            {

            }

        }

        public void ReadCallback(IAsyncResult ar)
        {
            try
            {
                String content = String.Empty;

                // Retrieve the state object and the handler socket  
                // from the asynchronous state object.  
                StateObject state = (StateObject)ar.AsyncState;
                Socket handler = state.workSocket;

                // Read data from the client socket.   
                int bytesRead = handler.EndReceive(ar);

                if (bytesRead > 0)
                {
                    // There  might be more data, so store the data received so far.  
                    state.sb.Append(Encoding.ASCII.GetString(
                        state.buffer, 0, bytesRead));

                    // Check for end-of-file tag. If it is not there, read   
                    // more data.  
                    content = state.sb.ToString();
                    if (content.IndexOf("<EOF>") > -1)
                    {
                        // All the data has been read from the   
                        // client. Display it on the console.  
                        //Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",content.Length, content);
                        // Echo the data back to the client.

                        //Choose what to do with the packet
                        string callBack= ClientController.GenerateResponseTo(content);
                        //Choose what server has to reply to client
                        Send(handler, @callBack+"*<EOF>");
                        //Send(handler, @"N:\tmp\2parts\save.cnf*1*<EOF>");
                    }
                    else
                    {
                        // Not all data received. Get more.  
                        handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                        new AsyncCallback(ReadCallback), state);
                    }
                }
            }
            catch { }

        }

        private void Send(Socket handler, String data)
        {
            try
            {
                // Convert the string data to byte data using ASCII encoding.  
                byte[] byteData = Encoding.ASCII.GetBytes(data);

                // Begin sending the data to the remote device.  
                handler.BeginSend(byteData, 0, byteData.Length, 0,
                    new AsyncCallback(SendCallback), handler);
            }
            catch { }
        }

        private void SendCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.  
                Socket handler = (Socket)ar.AsyncState;

                // Complete sending the data to the remote device.  
                int bytesSent = handler.EndSend(ar);
                //Console.WriteLine("Sent {0} bytes to client.", bytesSent);

                handler.Shutdown(SocketShutdown.Both);
                handler.Close();

            }
            catch
            {
            }
        }


    }
}

一旦我在GUI客戶端可以連接到服務器以請求他們回答並且服務器回復睡眠數據包,直到用戶在GUI上輸入有效路徑並單擊START。

那也行得很好。

我的問題是,當客戶端成功連接時,它開始向服務器發送回調,服務器從我自己制作的自定義控件輸出進度條中的回調,並且“工作”但問題是:

如果我在服務器啟動選項卡上保留GUI。 一切正常,客戶得到他們的答案和服務器添加和更新客戶端的進度條。 但是當我將標簽控件更改為顯示所有客戶端的進度條的選項卡時,服務器會停止向客戶端發送任何回復。 即使我回到服務器啟動選項卡,它也不再回復。

我對此非常苛刻。 有誰知道我的錯誤來自哪里?

我還上傳了調試客戶端的一些圖片和我的問題:

客戶端連接到服務器並獲得答案:

客戶端連接到服務器並獲得答案

更改GUI選項卡和服務器停止:

更改GUI選項卡和服務器停止

問題解決了。 感謝Aram Kocharyan和Mong Zhu。

錯誤是我試圖從不同的線程訪問GUI元素。 要從另一個線程修改GUI元素,必須使用controll的Invoke方法(Invoke從擁有該組件的線程調用該方法)

例:

Form1.GetInstance.flowLayoutPanel_progress.Invoke(
                new Action(() => Parse0(splited[1], out toReturn)));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM