Server Socket无法接受客户端。 (C#UWP异步套接字编程)

时间:2017-11-21 06:00:00

标签: server uwp

我使用C#Socket创建了一个Async Server套接字代码。

虽然我写了一段代码,然后测试到Console Environment,

它正在运行,但我在UWP测试了该代码。

但是,它没有用。不能接受客户。

Bind,Listen,Accept没有任何错误,但是这个套接字代码不能接受客户端!

我怎么能解决我?请帮帮我..

    private Socket m_ServerSocket;
    private List<Socket> m_ClientSocket;

    private int m_iPort = 1123;
    private int m_iClients = 8;
    private int m_iBufferSize = 128;

public bool Open(int IN_iPort, int IN_iClients, int IN_iBufferSize)
    {
        try
        {
            m_iPort = IN_iPort;
            m_iClients = IN_iClients;
            m_iBufferSize = IN_iBufferSize;

            m_ClientSocket = new List<Socket>();

            m_ServerSocket = new Socket(
                                AddressFamily.InterNetwork,
                                SocketType.Stream,
                                ProtocolType.Tcp);

            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, m_iPort);
            m_ServerSocket.Bind(ipep);
            m_ServerSocket.Listen(m_iClients);

            SocketAsyncEventArgs args = new SocketAsyncEventArgs();
            args.Completed
                += new EventHandler<SocketAsyncEventArgs>(Accept_Completed);
            m_ServerSocket.AcceptAsync(args);
        }
        catch (Exception e)
        {
            return false;
        }

        m_bIsOpen = true;
        return true;
    }

    private void Accept_Completed(object sender, SocketAsyncEventArgs e)
    {
        Socket ClientSocket = e.AcceptSocket;
        m_ClientSocket.Add(ClientSocket);

        if (m_ClientSocket != null)
        {
            SocketAsyncEventArgs args = new SocketAsyncEventArgs();
            byte[] szData = new byte[m_iBufferSize];
            args.SetBuffer(szData, 0, m_iBufferSize);
            args.UserToken = m_ClientSocket;
            args.Completed
                += new EventHandler<SocketAsyncEventArgs>(Receive_Completed);
            ClientSocket.ReceiveAsync(args);
        }

        e.AcceptSocket = null;
        m_ServerSocket.AcceptAsync(e);
    }

1 个答案:

答案 0 :(得分:1)

我检查了您的代码,代码中似乎没有问题。请检查您是否在项目appxmanifest中选中了Internet(Clent&Server)选项。有关更多详细信息,请参阅Sockets官方文档。