簡體   English   中英

從服務器發送消息到客戶端c#

[英]Send message from server to client c#

我在c#中創建了一個服務器 - 客戶端應用程序。 我設法將消息從客戶端發送到服務器並讀取它們,但我不知道如何將消息從服​​務器發送回客戶端。

這是我的服務器: 在此輸入圖像描述

namespace TCPSockets {
    public partial class Form1 : Form {

        TcpClient client = null;
        TcpListener listener = null;
        IPAddress ip = null;
        int port = 1337;

        Thread thClient = null;
        Thread thListener = null;


        NetworkStream dataStream = null;


        public Form1() {
            InitializeComponent();
            txt_ip.Text = "127.0.0.1";
            txt_port.Text = "1234";
        }

        private void ListenForConnections() {
            listener = new TcpListener(ip, port);
            listener.Start();

            while (true) {
                try {
                    client = listener.AcceptTcpClient(); 


                    dataStream = client.GetStream();

                    byte[] message = new byte[1024];
                    dataStream.Read(message, 0, message.Length);
                    dataStream.Close();

                    string strMessage = Encoding.UTF8.GetString(message);
                    MessageBox.Show("Server: I got message: " + strMessage);
                }

                catch (Exception ex) {
                    thListener.Join();  
                }
            }
        }




        private void start_server_Click(object sender, EventArgs e)
        {
            ip = IPAddress.Parse(txt_ip.Text);
            port = Convert.ToInt32(txt_port.Text);

            // nit => sicer vmesnik blokira, ko kličemo AcceptTcpClient()
            thListener = new Thread(new ThreadStart(ListenForConnections));
            thListener.IsBackground = true;
            thListener.Start();
        }
    }
}

這是我的客戶: 在此輸入圖像描述

namespace TCPSockets {
    public partial class Form1 : Form {

        TcpClient client = null;
        TcpListener listener = null;
        IPAddress ip = null;
        int port = 1337;


        Thread thClient = null;
        Thread thListener = null;


        NetworkStream dataStream = null;


        public Form1() {
            InitializeComponent();
            txt_ip.Text = "127.0.0.1";
            txt_port.Text = "1234";
        }


        private void SendPacket(object pClient) {
            string message = txt_message.Text;

            try {
                client = (TcpClient)pClient; 
                client.Connect(ip, port);   

                dataStream = client.GetStream();
                byte[] strMessage = Encoding.UTF8.GetBytes(message);
                dataStream.Write(strMessage, 0, strMessage.Length);
                dataStream.Close(); 
                client.Close();  
            }
            catch (Exception ex) {
                MessageBox.Show("Odjemalec: Pošiljanje ni bilo uspešno!");
            }
        }


        private void send_to_server_Click(object sender, EventArgs e)
        {
            ip = IPAddress.Parse(txt_ip.Text);
            port = Convert.ToInt32(txt_port.Text);

            client = new TcpClient();
            thClient = new Thread(new ParameterizedThreadStart(SendPacket));
            thClient.IsBackground = true;
            thClient.Start(client);

        }
    }
}

有誰知道如何從服務器正確地向客戶端發送消息並在客戶端中讀取它?

如果要使用當前使用的相同代碼,則只需在“服務器”和“客戶端”計算機上實現服務器客戶端角色。 然后,當您希望“服務器”計算機發送時,它將充當客戶端角色並發送到充當服務器角色的“客戶端”計算機。 您將需要兩台計算機監聽另一台計算機的消息。 我建議他們也在不同的端口上監聽,這樣你就不必修改代碼了。 基於托比亞斯的評論,可能會導致更多的復雜性,這就是為什么我建議使用SignalR,但這不是這個問題的答案,它是另一種選擇。

如果您不介意使用新的代碼庫,我強烈建議您探索的一種解決方案是SignalR。 SignalR是一種技術,允許“推送”通知,並允許您輕松完成您的目標。 這是一個很簡單的例子:

https://github.com/SignalR/Samples/tree/master/Samples_2.1.0/ConsoleClient

這將允許您像以下一樣簡單地調用消息:

await _connection.Send(new { Type = "sendToMe", Content = "Hello World!" });

在許多平台上得到了支持,並且有很多教程

這是GitHub上示例存儲庫的鏈接。 這里概述了使用SignalR執行此操作的另一種方法以及OWIN Self Hosting方法: SignalR Console應用程序示例

當服務器(TcpListener)接受來自客戶端(TcpClient)的傳入連接時,它將創建服務器端TcpClient。 請參閱MSDN TcpListener.AcceptTcpClient

因此,您將擁有其中兩個:一個是您在客戶端程序中創建的,另一個是由TcpListener自動創建的。

只需使用TcpClient.GetStream()在兩者上獲取底層網絡流,您就可以使用NetworkStream.Read()和.Write()進行通信。 而已。

為了測試和調試網絡連接,我建議使用HWGroup Hercules和SysInternals TcpView。

暫無
暫無

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

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