多客户端

时间:2018-01-24 09:07:49

标签: c# sockets

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace sockasyncsrv
{
    class Program
    {
        static void Main(string[] args)
        {
            RunAsyncSocketServer().Wait();
        }

        static async Task RunAsyncSocketServer()
        { 
            int MAX_SIZE = 1024; 

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


            IPEndPoint ep = new IPEndPoint(IPAddress.Any, 7000);
            sock.Bind(ep);

            sock.Listen(100);

            while (true)
            {
                Socket clientSock = await Task.Factory.FromAsync(sock.BeginAccept, sock.EndAccept, null);

                var buff = new byte[MAX_SIZE];

                int nCount = await Task.Factory.FromAsync<int>(
                           clientSock.BeginReceive(buff, 0, buff.Length, SocketFlags.None, null, clientSock),
                           clientSock.EndReceive);

                if (nCount > 0)
                {
                    string msg = Encoding.ASCII.GetString(buff, 0, nCount);
                    Console.WriteLine(msg);

                    await Task.Factory.FromAsync(
                            clientSock.BeginSend(buff, 0, buff.Length, SocketFlags.None, null, clientSock),
                            clientSock.EndSend);
                }

                clientSock.Close();
            }
        }
    }
}

客户端连接我的服务器后,我想继续从连​​接的客户端接收消息。所以我使用了&#39;而(真实)&#39;如果(nCount> 0)&#39;,则无法接受其他客户端。如何获得多客户端?

1 个答案:

答案 0 :(得分:2)

您需要多个套接字才能进行多个连接。 Soket是设计用于处理一个连接的设计。你可以创建一个新的Socket,一旦第一个有连接就等待连接。(线程进入while(true)循环)

您也可以同时收听多个套接字。 Maby在另一个港口?像这样的东西。

    static async Task RunAsyncSocketServer(int port)
    {
        int MAX_SIZE = 1024;

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


        IPEndPoint ep = new IPEndPoint(IPAddress.Any, port);