创建多客户端连接服务端。
不管是服务端还是客户端都必须引用:
using System.Net;
using System.Net.Sockets;
创建服务器代码:
class Program
{
static void Main(string\[\] args)
{
IPAddress ip = new IPAddress(new byte\[\] { 127, 0, 0, 1 });
//IP 创建的方式
//IPAddress ip1 = IPAddress.Parse("127.0.0.1");
//IPAddress ip2 = Dns.GetHostEntry("localhost").AddressList\[0\];
TcpListener listener = new TcpListener(ip, 8001);
listener.Start();
Console.WriteLine("Server start listen ...");
while (true)
{
TcpClient client = listener.AcceptTcpClient();
Console.WriteLine($"Client Connected. {client.Client.LocalEndPoint} <-- {client.Client.RemoteEndPoint} ");
}
}
}
创建客户端代码,创建多个客户端实例:
//创建多个客户端
static void Main(string\[\] args)
{
Console.WriteLine("多个客户端连接服务器");
Console.WriteLine("Running......");
TcpClient client;
for (int i = 0; i <= 2; i++)
{
try
{
client = new TcpClient();
client.Connect(new IPAddress(new byte\[\] { 127, 0, 0, 1 }), 8001);
Console.WriteLine($"Connected. {client.Client.LocalEndPoint} -->{client.Client.RemoteEndPoint}");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
Console.WriteLine($"\\n\\n输入 Q 键退出");
ConsoleKey key;
do
{
key = Console.ReadKey(true).Key;
}
while (key != ConsoleKey.Q);
}
先开启服务器软件,再执行客户端软件。
再循环体内创建了3个TcpClint 实例,都是连接到同一个服务器(相同的IP+Port),测试连接OK。