Асинхронный сокет: подключение нескольких клиентов - C#
Формулировка задачи:
Как сделать что-бы к серверу подключалось сразу несколько клиентов. Что я не так сделал? Как это исправить?
class Program
{
public static void ReceiveCallback(IAsyncResult AsyncCall)
{
string nameDoname; //имя домена
int port; //порт сайта
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
// byte[] messageSend = Encoding.UTF8.GetBytes("Занят");
byte[] messageRecv = new byte[124];
Socket listener = (Socket)AsyncCall.AsyncState;
Socket client = listener.EndAccept(AsyncCall);
Console.WriteLine("Client: " + client.RemoteEndPoint.ToString());
string Recv = null;
while (true)
{
int length = client.Receive(messageRecv);
string rec = Encoding.UTF8.GetString(messageRecv);
Recv = Recv + rec;
if (length < 124)
{
//Console.WriteLine(Recv);
break;
}
}
//Console.WriteLine(Recv);
string host;
string[] hostPort;
//вычисляем имя хоста с принятых данных и порт если он имеется
if(Host(Recv, out host))
{
hostPort = host.Split(':');
nameDoname = hostPort[0];
if (hostPort.Length > 1)
{
if (hostPort[1] == null)
port = 80;
else
port = Int32.Parse(hostPort[1]);
}
else
port = 80;
Console.WriteLine("host: {0}\n port: {1}", nameDoname, port);
Connect(port, nameDoname, Recv, client);
}
Console.WriteLine("Закрытие соединения " + host);
client.Close();
// listener.BeginAccept(new AsyncCallback(ReceiveCallback), listener);
}
public static void Main()
{
try
{
IPAddress localAddress = IPAddress.Parse("127.0.0.1");
Socket listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipEndpoint = new IPEndPoint(localAddress, 2200);
listenSocket.Bind(ipEndpoint);
listenSocket.Listen(1);
listenSocket.BeginAccept(new AsyncCallback(ReceiveCallback), listenSocket);
Console.WriteLine("Ожидание соединения… {0}", listenSocket.LocalEndPoint);
while (true)
{
listenSocket.BeginAccept(new AsyncCallback(ReceiveCallback), listenSocket);
}
}
catch (Exception e)
{
Console.WriteLine("Произошла ошибка: {0}", e.ToString());
}
}
public static void Connect(int port, string nameDoname, string recv1, Socket clientRecv)
{
byte[] recv = Encoding.UTF8.GetBytes(recv1);
byte[] ipByte = new byte[4];
int[] ipInt = new int[4];
byte[] messageRead;
byte[] messageReadchank;
string prowNaSimv = nameDoname.Substring(nameDoname.Length - 1);
if (prowNaSimv == "\r")
{
nameDoname = nameDoname.Substring(0, nameDoname.Length - 1);
}
string ip = Dns.GetHostEntry(nameDoname).AddressList[0].ToString();
Console.WriteLine(ip);
TcpClient client = new TcpClient();
string[] ipName = ip.Split('.');
for (int i = 0; i < ipName.Length; i++)
{
ipInt[i] = Int32.Parse(ipName[i]);
ipByte[i] = Convert.ToByte(ipInt[i]);
}
try
{
client.Connect(new IPAddress(ipByte), port);
NetworkStream stream = client.GetStream();
stream.Write(recv, 0, recv.Length); //отправляем данные на сайт которые пришли с браузера
int byteRead;
while (true)
{
try
{
byteRead = 0;
messageRead = new byte[1024];
byteRead = stream.Read(messageRead, 0, messageRead.Length); //считываем данные
string Recv = Encoding.UTF8.GetString(messageRead);
messageReadchank = new byte[byteRead];
messageReadchank = messageRead;
clientRecv.Send(messageReadchank, byteRead, SocketFlags.None); //передаём данные
if (byteRead < 1024)
{
client.Close();
break;
}
Thread.Sleep(100);
}
catch (Exception)
{
client.Close();
break;
// Console.WriteLine(e.ToString());
}
}
Console.WriteLine("Передали.");
}
catch (Exception e) { }
}
public static bool Host(string line, out string host)
{
string[] adresSplit = line.Split('\n');
if (line == null)
{
throw new ArgumentNullException("null");
}
host = null;
for (int i = 0; i < adresSplit.Length; i++)
{
if (adresSplit[i].StartsWith("Host: "))
{
host = adresSplit[i].Substring("Host: ".Length);
return true;
}
}
return false;
}
}Решение задачи: «Асинхронный сокет: подключение нескольких клиентов»
textual
Листинг программы
listenSocket.Listen(1);