C ++异步套接字(System.Net.Sockets.Socket.BeginAccept)与WinSock2.h [英] C++ Async Sockets (System.Net.Sockets.Socket.BeginAccept) with WinSock2.h

查看:423
本文介绍了C ++异步套接字(System.Net.Sockets.Socket.BeginAccept)与WinSock2.h的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在制作一个C ++应用程序(以提高我的C ++)。
我创建了一个套接字服务器,但我被困住了。

I'm currently making a C++ app (to improve my C++). I'm creating a socket server but I'm stuck.

我如何在C#中执行:

using System;
using System.Net;
using System.Net.Sockets;

namespace Network
{
    class HTcpListener
    {
        private Socket mSocket;

        public HTcpListener(int port)
        {
            IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, port);
            mSocket = new Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.tcp);
            mSocket.Bind(endpoint);
            mSocket.Listen(10);
            mSocket.BeginAccept(new AsyncCallback(OnAccept));
        }

        private void OnAccept(IAsyncResult iAr)
        {
            // Handle connection and start up game

            mSocket.BeginAccept(new AsyncCallback(OnAccept));
        }
    }
}

。在WinSock2.h有一个名为accept的函数,但我想知道它是否与BeginAccept一样,如果没有,如何使它的功能像在我的C#示例中。它必须能够同时处理多个套接字+多个套接字。

But now I'm wondering. In WinSock2.h there's a function called accept, but I'm wondering if it works the same as BeginAccept, and if not, how to make it function like it would in my C# example. It must have the ability to handle multiple sockets at the same time + more than 1 socket.

推荐答案

.NET的异步API套接字下使用的套接字是 I / O完成端口结合 AcceptEx 和朋友。这些通常用于需要高性能,可扩展I / O的应用程序中。这些有点比.NET包装更多的使用,但如果你习惯于.NET的APM模式,你已经在一半了。

The APIs that .NET's async sockets use under the hood are I/O Completion Ports combined with AcceptEx and friends. These are commonly used in apps requiring high-performance, scalable I/O. These are a bit more involved to use than the .NET wrappers, but you're already halfway there if you're accustomed to .NET's APM pattern.

Adam的建议使用非阻塞套接字也会工作得很好,只是具有显着较少的可扩展性。不要让你阻止你检查它们,因为它们足够适合大多数应用程序,更容易移植到其他操作系统上可用的。

Adam's suggestion to use a non-blocking socket will work fine too, just with significantly less scalability. Don't let that discourage you from checking them out though, as they're good enough for most apps and more easily ported to what's available on other operating systems.

A更多以C ++为中心和完全可移植的方法将类似于 Asio ,它使用类似于APM的回调系统。非常推荐。

A more C++-centric and fully portable approach would be something like Asio, which uses a callback system similar to APM. Highly recommend it.

这篇关于C ++异步套接字(System.Net.Sockets.Socket.BeginAccept)与WinSock2.h的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆