【问题标题】:Why must I every time initialize tcpClient and networkStream to send data to server?为什么我每次都必须初始化 tcpClient 和 networkStream 才能将数据发送到服务器?
【发布时间】:2016-02-28 05:11:18
【问题描述】:

我是 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 方法中的行中删除 cmets 时,msg 已发送。
服务器端应用程序可以获取并显示 clinet 消息。
那么问题是什么?为什么我必须再次启动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);
    }
  }                
}

【问题讨论】:

  • 服务器可能会关闭连接,它可能会超时,也许您更改了txtRemoteIp.Text...问题可能是其中之一。你能显示服务器代码吗?你调用butConnect_Click 方法吗?你能解释一下为了重现它而采取的确切步骤吗?

标签: c# sockets tcp network-programming networkstream


【解决方案1】:

您创建服务器的方式是每次都等待新的连接。你可以拿

TcpClient client = listener.AcceptTcpClient();

退出你的while循环。它会按需要工作。否则您每次都需要连接并发送消息,这没有错。如果您将 acceptTcpClient 退出循环,您的服务器将只为一个客户端工作。

Simple Socket Listener

【讨论】:

  • 我不明白为什么它不发送。当我调试代码时,我看到 client 和 ns 变量不为空..
  • 是的,对不起,我以为是WebForms,我试着在这里模拟问题。尝试在您的发送方法中放置一个 try/catch 块。并告诉我们是否发生了一些异常
  • 我确实在 butSend 方法中放了 try catch,但它没有给出任何异常.. :(
猜你喜欢
  • 2017-04-19
  • 2016-01-08
  • 1970-01-01
  • 2022-01-15
  • 2020-05-31
  • 1970-01-01
  • 2022-08-12
  • 2013-07-14
  • 1970-01-01
相关资源
最近更新 更多