c# - C# 中的套接字编程这被认为是轮询吗?
问题描述
所以我一直在尝试使用在线找到的代码在 C# 中进行套接字编程。从https://www.geeksforgeeks.org/socket-programming-in-c-sharp/查看此代码时
public static void ExecuteServer()
{
// Establish the local endpoint
// for the socket. Dns.GetHostName
// returns the name of the host
// running the application.
IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddr = ipHost.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddr, 11111);
// Creation TCP/IP Socket using
// Socket Class Costructor
Socket listener = new Socket(ipAddr.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
try {
// Using Bind() method we associate a
// network address to the Server Socket
// All client that will connect to this
// Server Socket must know this network
// Address
listener.Bind(localEndPoint);
// Using Listen() method we create
// the Client list that will want
// to connect to Server
listener.Listen(10);
while (true) {
Console.WriteLine("Waiting connection ... ");
// Suspend while waiting for
// incoming connection Using
// Accept() method the server
// will accept connection of client
Socket clientSocket = listener.Accept();
// Data buffer
byte[] bytes = new Byte[1024];
string data = null;
while (true) {
int numByte = clientSocket.Receive(bytes);
data += Encoding.ASCII.GetString(bytes,
0, numByte);
if (data.IndexOf("<EOF>") > -1)
break;
}
Console.WriteLine("Text received -> {0} ", data);
byte[] message = Encoding.ASCII.GetBytes("Test Server");
// Send a message to Client
// using Send() method
clientSocket.Send(message);
// Close client Socket using the
// Close() method. After closing,
// we can use the closed Socket
// for a new Client Connection
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
}
}
catch (Exception e) {
Console.WriteLine(e.ToString());
}
}
}
}
我想知道这部分是否
while (true) {
int numByte = clientSocket.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, numByte);
if (data.IndexOf("<EOF>") > -1)
break;
}
被认为是一种轮询方法,也是我们不简单使用的原因
int numByte = clientSocket.Receive(bytes);
data = Encoding.ASCII.GetString(bytes, 0, numByte);
我已经尝试了上述方法,它似乎工作得一样好。那么我们使用依赖于文本停止阅读的无限while循环是有原因的吗?我找到了许多似乎使用这种方法的来源。为什么会这样?
解决方案
推荐阅读
- plotly - 我如何在我的情节 go.scatter3d() 中显示点
- excel - Excel VBA - XML 没有一致地将数据抓取到 Excel 中
- firebase - 将 Firebase 数组映射到列表中 Flutter
- bash - linux bash变量根据范围产生2个不同的值?
- c - 预处理器存储的宏定义
- lua - 如何在 roblox lua 中找到角色部分的方向?
- javascript - 我将如何使用下划线 js 将嵌套 json 转换为扁平 json
- symfony - 在 Symfony 的 CheckboxType 中将字符串填充为布尔值
- php - 从 PHP 应用程序运行并行 CLI 进程的最有效方法
- python - Sqlite 日期时间与 unix 时间戳的比较