C# 从 TcpClient 读取流

标签 c# tcpclient streamreader

我正在制作一个服务器 - 使用 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:客户端和服务器是 2 个不同的项目。

最佳答案

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

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();

希望我能理解您的需求。

关于C# 从 TcpClient 读取流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39961811/

相关文章:

c# - StreamReader 获取和设置位置

c# - 改进算法执行时间

c# - 为什么要在任务中使用多个重复的方法实现?

c# - 套接字服务器 : Manage client connections

c# - TCP 客户端问题

c# - 单独线程中 TCPClient 的内存泄漏

c# - Cast uint -> double 无效?

c - TCP 客户端 - 从未知/无限大小接收消息

c# - 以非升序从大文件中读取多行

c# - StreamReader 卡在大文件上