【问题标题】:C# Reading stream from TcpClientC# 从 TcpClient 读取流
【发布时间】:2021-08-16 19:18:27
【问题描述】:

我正在使用TcpClient 和服务器制作一个服务器 - 客户端程序。

从我使用的服务器发送:

static void send(string data)
{
    sw.WriteLine(data + Environment.NewLine);   
}

当客户端连接时,我正在发送一些文本:

client = listener.AcceptTcpClient();
sr = new StreamReader(client.GetStream());
sw = new StreamWriter(client.GetStream());

string line;

try 
{
    send("Hello world");
} //More code

并从客户端读取:

string data;
data = sr.ReadLine();

if(data != string.Empty || data != null)
{
    MessageBox.Show(data);
}

我尝试放入 while(true) 并且它冻结了,我尝试放入一个计时器滴答循环并且它冻结了...

我该如何解决这个问题?

P.S:客户端和服务端是两个不同的项目。

【问题讨论】:

  • 冻结在哪一行?哪一行抛出导致崩溃的异常?
  • 不抛出异常,程序只是冻结
  • 你说你把它放在“一个计时器滴答循环中,它崩溃了”。如果您在调试器中单步执行代码,第一个问题仍然存在,它会冻结在哪一行?
  • 对不起,这是一个错字,我得到了与 while(true) 循环相同的结果,它只是冻结,直到我关闭程序/服务器
  • 请使用调试器单步执行每一行,并在挂起/冻结之前告诉我们它在哪一行执行。

标签: c# tcpclient streamreader


【解决方案1】:

我相信你需要这样的东西:

try
{
     listen = new TcpListener(myAddress, port);
     listen.Start();
     Byte[] bytes;
     while (true)
     {
         TcpClient client = listen.AcceptTcpClient();
         NetworkStream ns = client.GetStream();
         if(client.ReceiveBufferSize > 0){
             bytes = new byte[client.ReceiveBufferSize];
             ns.Read(bytes, 0, client.ReceiveBufferSize);             
             string msg = Encoding.ASCII.GetString(bytes); //the message incoming
             MessageBox.Show(msg);
         }
      }
}
catch(Exception e)
{ 
  //e
}

然后将这段代码作为后台线程:

Thread thread = new Thread(the functions name);
thread.IsBackground = true;
thread.Start();

希望我能理解您的需求。

【讨论】:

  • 我说客户端和服务端不在同一个项目,它们是2个不同的程序
  • 你缺少一个大括号,同时你应该检查你是否从调用 ns.Read 中得到任何东西,否则你将创建一堆空字符串
  • 从你说的看来,这似乎是对的,也许可以添加更多细节?
  • 我希望服务器和客户端是单独的程序
  • 谢谢,这正是我需要的:)
【解决方案2】:

试试这个,爷爷的方法。

                int i = 0;
                while (stream.DataAvailable == true)
                {
                    bytes[i] = ((byte)stream.ReadByte());
                    i++;
                }

                data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                Console.WriteLine("Received: {0}", data);

【讨论】:

    猜你喜欢
    • 2016-01-15
    • 1970-01-01
    • 1970-01-01
    • 2011-09-04
    • 2013-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多