0

メイン アプリケーションから C# サーバーを実行しており、サーバー スレッドから受信したメッセージをメイン スレッドに渡したいと考えています。サーバーは、新しい接続のためにバックグラウンドで実行されている必要があります。新しい接続があるたびに、サーバーは受信したメッセージをメイン アプリに渡す必要があります。メッセージが受信されたときにメインアプリに知らせるにはどうすればよいですか? また、新しい接続があるときにサーバースレッドからメインにメッセージを渡すにはどうすればよいですか?

主な用途

  public partial class MainWindow : Window
 {
        TCPServer Server = new TCPServer(); //start running the server
        //get the message (Server.message) when a client sent it to the server
        //TODO process the message
    }

TCP サーバー

class TCPServer
    {
        private TcpListener tcpListener;
        private Thread listenThread;
        private String message;

        public TCPServer()
    {
        this.tcpListener = new TcpListener(IPAddress.Any, 3200);
        this.listenThread = new Thread(new ThreadStart(ListenForClients));
        this.listenThread.Start();

    }

 //starts the tcp listener and accept connections
    private void ListenForClients()
    {
        this.tcpListener.Start();

        while (true)
        {
            //blocks until a client has connected to the server
            System.Diagnostics.Debug.WriteLine("Listening...");
            TcpClient client = this.tcpListener.AcceptTcpClient();
            System.Diagnostics.Debug.WriteLine("Client connected");


            //create a thread to handle communication 
            //with connected client
            Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
            clientThread.Start(client);
        }
    }


    //Read the data from the client
    private void HandleClientComm(object client)
    {

        TcpClient tcpClient = (TcpClient)client; //start the client
        NetworkStream clientStream = tcpClient.GetStream(); //get the stream of data for network access

        byte[] message = new byte[4096];
        int bytesRead;

        while (true) 
        {
            bytesRead = 0;

            try
            {
                //blocks until a client sends a message
                bytesRead = clientStream.Read(message, 0, 4096);
            }
            catch
            {
                //a socket error has occured
                break;
            }

            if (bytesRead == 0) //if we receive 0 bytes
            {
                //the client has disconnected from the server 


          break;
                }
                //message has successfully been received
                ASCIIEncoding encoder = new ASCIIEncoding();
                message = encoder.GetString(message, 0, bytesRead);

                //Reply
                byte[] buffer = encoder.GetBytes("ACK");
                clientStream.Write(buffer, 0, buffer.Length);
                System.Diagnostics.Debug.WriteLine("ACK");
                clientStream.Flush();
               }
            tcpClient.Close();
            System.Diagnostics.Debug.WriteLine("Client disconnected");
        }
4

2 に答える 2

1

これは TcpListener によってすでに十分にサポートされています。代わりに BeginAcceptTcpClient() メソッドを使用してください。WPF または Winforms アプリのメイン スレッドから呼び出すと、コールバックは同じメイン スレッドで自動的に実行されます。同じことが BeginReceive() メソッドにも当てはまります。内部的には、ディスパッチャー ループを使用してコールバック メソッドをアクティブにします。これは、BackgroundWorker のようなクラスや C# v5 の async/await キーワードが機能する方法とよく似ています。

これにより、独自のスレッドを開始して終了し、適切にマーシャリングして戻すという面倒な作業から解放されます。また、プログラムのリソース使用量を大幅に削減します。強くお勧めします。

于 2013-05-08T23:44:19.897 に答える
0

キューが答えです。具体的には、この場合はConcurrent Queueです。

ソケット スレッドがメッセージをキューに入れます。ワーカー スレッドがキューをポーリングし、作業項目を取り出します。

ソケットベースのアプリケーションでは、このパターンは非常に一般的です。

または、システム スレッド プールに対してQueueUserWorkItemを実行して、作業負荷を管理することもできます。

注: 現在、マルチスレッドの世界にいます。発生する同期およびその他の問題について読む必要があります。これを怠ると、アプリに非常に奇妙なバグが発生することになります。

于 2013-05-08T23:47:52.373 に答える