C# 客户端怎么循环创建Socket连接?比如说创建10个 然后进行连接

2025-02-24 05:05:38
推荐回答(1个)
回答1:

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

class ClientSockets
{
    //socket数组
    Socket[] sockets;
    // 构造函数
    public ClientSockets()
    {
        sockets = new Socket[10];
        for (int i = 0; i < sockets.Length; i++)            
        {                
            sockets[i] = new Socket(
                AddressFamily.InterNetwork, 
                SocketType.Stream, 
                ProtocolType.Tcp);                
            sockets[i].Bind(new IPEndPoint(IPAddress.Any, 0));
        }
    }
    // 让10个socket连接指定的IP和端口
    public void Connect(string remoteIP, int remotePort)
    {
        IPEndPoint remoteEP = 
            new IPEndPoint(IPAddress.Parse(remoteIP), remotePort);
        for (int i = 0; i < sockets.Length; i++)
        {
            sockets[i].Connect(remoteEP)
        }
    }
    
    public void Close()
    {
        for (int i = 0; i < sockets.Length; i++)
        {
            sockets[i].Shutdown(SocketShutdown.Both);
            sockets[i].Close();
        }
    }
    
    
    // 获取指定序号的Socket
    public Socket GetSocket(int index)
    {
        if(index >=0 && index < 10)
        {
            return socket[index];
        }
        else
        {
            return null;
        }            
    }
    
    // 获取Socket的数量
    public int Count
    {
        get { return 10;}
    }
}
// ======================================================
//使用 ClientSockets
//=======================================================
class Program
{
     static void Main()
     {
         ClientSockets sockets = new ClientSockets();
         string remoteIP = "192.168.1.100";
         sockets.Connect(remoteIP, 8080);
         
         for( int i = 0; i < sockets.Count; i++)
         {
             if(sockets[i].Connected)
             {
                 ConsoleWriteLine("Socket[{0}]连接成功", i);
             }
             else
             {
                 ConsoleWriteLine("Socket[{0}]连接失败", i);
             }
         }
         
         //其余代码略……
         
         //关闭
         sockets.Close();
     }
}