簡體   English   中英

為什么每次都要初始化tcpClient和networkStream來將數據發送到服務器?

[英]Why must I every time initialize tcpClient and networkStream to send data to server?

我是C#中網絡編程的新手。
因此,我決定編寫一個簡單的服務器-客戶端Winform應用程序。
我使用TcpListener,TcpClient,NetworkStream。
以下是我從“客戶端應用程序”獲得的代碼片段。

TcpCLient client;
NetworkStream ns;

private void butConnect_Click(object sender, EventArgs e)
{
    string remoteIp = txtRemoteIp.Text;
    int port = 4848;
    client = new TcpClient(remoteIp, port);
    ns = client.GetStream();           
}

private void butSend_Click(object sender, EventArgs e)
{
    string msg = txtMessage.Text;

    //string remoteIp = txtRemoteIp.Text;
    //int port = 4848;
    //client = new TcpClient(remoteIp, port);
    //ns = client.GetStream();

    byte[] buffer = Encoding.ASCII.GetBytes(msg);
    ns.Write(buffer, 0, buffer.Length);

    txtMessage.Clear();
}

如您所見,我在butConnect方法中啟動了clientns 當我嘗試在butSend方法中發送某些msg時,服務器端應用程序無法讀取它。
但是,當我從butsend方法中的行中刪除注釋時,發送了msg
服務器端應用程序可以獲取並顯示客戶端消息。
那是什么問題呢? 為什么我必須再次初始化clientns變量?

這是服務器端代碼。

public FormServer() //this is constructor
{
    InitializeComponent();
    initControls();


    ipAddr = IPAddress.Parse(txtIpAddress.Text);
    port = 4848;
    listener = new TcpListener(ipAddr, port);
    listener.Start();

    Thread t = new Thread(Run);
    t.Name = "ListenerThread";
    t.Start(); 
}

private void Run()
{
    while (true)
    {
        while (!listener.Pending())
        {
             Thread.Sleep(200);
        }

    Action<string> action = (string s) => listStatus.Items.Add(s);
    client = listener.AcceptTcpClient();

    try
    {
        NetworkStream ns = client.GetStream();

        byte[] buffer = new byte[1024];
        ns.Read(buffer, 0, 1024);
        string msg = Encoding.ASCII.GetString(buffer);

        listStatus.Invoke(action, msg);
    }
    catch (Exception e)
    {
         System.Diagnostics.Debug.WriteLine(e.Message);
    }
  }                
}

您創建服務器的方式是每次都等待新連接。 你可以采取

TcpClient client = listener.AcceptTcpClient();

在您的while循環之外。 並且它將按需工作。 否則,您每次都需要連接並發送消息,這沒有錯。 而且,如果您將acceptTcpClient移出循環,則您的服務器將僅適用於一個客戶端。

簡單套接字監聽器

暫無
暫無

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

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