【发布时间】:2014-02-08 06:50:06
【问题描述】:
我必须使用只公开同步套接字接口的套接字库。我有几个问题将此同步转换为异步。我从msdn示例开始(库接口类似于microsoft socket库,只是库使用了不同的通信算法)。
这是我目前的进度
private async void Start_Click(object sender, RoutedEventArgs e)
{
Log("Start server");
var port = int.Parse(Port.Text);
var task = Task.Run(() =>
{
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
Log("Hostname " + Dns.GetHostName());
IPAddress[] ipv4Addresses = Array.FindAll(
Dns.GetHostEntry(string.Empty).AddressList,
a => a.AddressFamily == AddressFamily.InterNetwork);
IPAddress[] ipv6Addresses = Array.FindAll(
Dns.GetHostEntry(Dns.GetHostName()).AddressList,
a => a.AddressFamily == AddressFamily.InterNetworkV6);
foreach (var ip in ipv4Addresses)
{
Log("Ipv4 list " + ip);
}
foreach (var ip in ipv6Addresses)
{
Log("Ipv6 list " + ip);
}
var localEndPoint = new IPEndPoint(IPAddress.Any, port);
Log("Ip " + IPAddress.Any);
Log("Port " + port);
// Create a TCP/IP socket.
var listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and
// listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen((int)SocketOptionName.MaxConnections);
Log("Max connection " + (int)SocketOptionName.MaxConnections);
// Start listening for connections.
bool isContinue = true;
while (isContinue)
{
Log("Waiting for a connection...");
// Program is suspended while waiting for an incoming connection.
var handler = listener.Accept();
// handle connection
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
string data;
Log("Connection accepted");
Log("Local endpoint " + handler.LocalEndPoint);
Log("Remote endpoint " + handler.RemoteEndPoint);
data = null;
// An incoming connection needs to be processed.
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf("<EOF>") > -1)
{
break;
}
}
// Show the data on the console.
Log("Text received " + data);
// Echo the data back to the client.
byte[] msg = Encoding.ASCII.GetBytes(data);
handler.Send(msg);
Log("Message sent");
handler.Shutdown(SocketShutdown.Both);
Log("Shutdown");
handler.Close();
Log("Close");
isContinue = true;
}
}
catch (Exception ex)
{
Log(ex.ToString());
}
});
await task;
}
- 当我有 2 个或更多并发客户端时会发生什么?
- 当第一个连接忙于通信时,第二个连接发生了什么?
- 监听器在 listener.Accept() 之后是否立即监听?
- 假设我有 4 个逻辑核心,当我在 4 个线程上侦听每个具有不同端口号的线程时会发生什么。每个侦听器都阻塞了 listener.Accept 中的线程。我的 ui 和 pc 会发生什么?它会挂起(所有核心都被使用和阻塞)吗?
- 有什么模式可以参考吗?
我正在考虑使用 Task、async、await,但我似乎无法在脑海中构建它。
我想通过添加套接字来改进这个库。
谢谢。
【问题讨论】:
-
感谢您的链接。
-
那么这个第 3 方库是否暴露了
Begin/End风格的 API? -
如果该代码来自 MSDN,他们应该删除该代码。不安全的处理,ASCII 编码,奇怪的 DNS 东西没有一点。不要太相信 MSDN。
-
@usr 在这方面我必须同意你的看法。
标签: c# sockets asynchronous