C# TcpClient: Listen for Incoming Data
In C#, you can use the TcpClient class to listen for incoming data. Here is an example code:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class TcpClientExample
{
public static void Main()
{
// 创建TcpClient对象,并连接到指定的IP地址和端口号
TcpClient client = new TcpClient();
client.Connect("127.0.0.1", 8080);
// 获取网络流对象
NetworkStream stream = client.GetStream();
// 接收数据的缓冲区
byte[] buffer = new byte[1024];
// 用于存储接收到的数据
StringBuilder data = new StringBuilder();
while (true)
{
// 读取网络流中的数据
int bytesRead = stream.Read(buffer, 0, buffer.Length);
// 如果没有数据可读,退出循环
if (bytesRead == 0)
{
break;
}
// 将接收到的数据转换为字符串并存储起来
data.Append(Encoding.ASCII.GetString(buffer, 0, bytesRead));
}
// 关闭网络流和TcpClient对象
stream.Close();
client.Close();
// 输出接收到的数据
Console.WriteLine("Received data: {0}", data.ToString());
}
}
In the above code, we start by creating a TcpClient object and connecting to a specified IP address and port number. Next, we obtain the network stream object from the TcpClient object and use the Read() method to read data from the network stream. The data read is stored in a StringBuilder object. Finally, we close the network stream and TcpClient object, and output the received data.