在我的一个项目中,我实现了一个小型HTTP服务器来流式传输连接的网络摄像头的视频数据 . 对于此任务,我正在使用.NET Framework 4.5中的System.Net.Sockets.TcpListener,它侦听预配置的 endpoints 并使用AcceptSocketAsync()mtehod等待发出请求 . 您可以在下面看到相关的代码部分:
this.server = new TcpListener(endpoint);
this.server.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, 0));
this.server.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
this.server.Start();
...
this.listenTask = Task.Factory.StartNew(this.Listen);
...
private async void Listen()
{
try
{
while (this.server.Server.IsBound)
{
Socket socket = await this.server.AcceptSocketAsync();
if (socket == null)
{
break;
}
Task.Factory.StartNew(() => this