Actually a subject. If there is an example I will be very grateful. Everywhere client-server is described for sockets;

UPD : there is an example, but it is only for one request

using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Windows.Forms; namespace AsyncSocketExample { public partial class Form1 : Form { private delegate void MyDelegate(object args); public Form1() { InitializeComponent(); } private void GetHtmlAsynh(string adress) //все что в этом методе было раньше в обработчике кнопки { if (String.IsNullOrEmpty(adress)) { MessageBox.Show("Необходимо указать url!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } int port = 80; // по умолчанию порт 80 Uri u = new Uri(textBox1.Text); // создаем сокет Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // инициализируем обработчик асихронных операций SocketAsyncEventArgs se = new SocketAsyncEventArgs(); // подключаем обработчики событий асинхронных запросов se.Completed += new EventHandler<SocketAsyncEventArgs>(OnSend); // цепляем точку доступа IPHostEntry hostEntry = Dns.GetHostEntry(u.Host); se.RemoteEndPoint = new IPEndPoint(hostEntry.AddressList[0], port); //se.UserToken = s; // создаем асихронное подключение s.ConnectAsync(se); } private void button1_Click(object sender, EventArgs e) { GetHtmlAsynh(textBox1.Text); } // обработчик асинхронных операций private string _requestResult = ""; private int total = 0; private void OnSend(object sender, SocketAsyncEventArgs e) { Socket s = (Socket)sender; // в sender будет передаваться экземпляр сокета, вызвавшего это событие // выводим информацию о текущей операции и результатах её выполнения if (e.SocketError == SocketError.Success) { //SetLabel(String.Format("Операция {0} успешно выполнена!", e.LastOperation)); } else { SetLabel(String.Format("Ошибка {1} при выполнении операции {0}...", e.LastOperation, e.SocketError)); } // -- // делаем что-нибудь, в зависимости от типа выполненной операции switch (e.LastOperation) { case SocketAsyncOperation.Connect: // если соединение установлено if (e.SocketError == SocketError.Success) { // отправляем запрос SendRequest(s, e); } break; case SocketAsyncOperation.Send: // если запрос отправлен без ошибок if (e.SocketError == SocketError.Success) { // получаем ответ от удаленного сервера byte[] buffer = new byte[4096];// размер пакета 4 кб e.SetBuffer(buffer, 0, buffer.Length); // аннулируем предыдущий результат, если был _requestResult = ""; total = 0; // получаем пачку ответа s.ReceiveAsync(e); } break; case SocketAsyncOperation.Receive: if (e.SocketError == SocketError.Success) { SetLabel(String.Format("Операция {0} успешно выполнена! Получено {1} байт, всего {2} байт", e.LastOperation, e.BytesTransferred, total + e.BytesTransferred)); // передаем результат в TextBox _requestResult += Encoding.UTF8.GetString(e.Buffer, 0, e.BytesTransferred); total += e.BytesTransferred; // слудующая пачка данных, если есть if (e.BytesTransferred > 0) { // нужно обнулить буфер, иначе куски данных могут попасть в следующий ответ byte[] buffer = new byte[4096]; e.SetBuffer(buffer, 0, buffer.Length); s.ReceiveAsync(e); } else { // нет данных, отключаемся s.Close(); textBox2.Invoke(new Action(() => { textBox2.Text = _requestResult; })); } } break; } } // метод отправляет запрос private void SendRequest(Socket s, SocketAsyncEventArgs e) { // формируем HTTP-запрос Uri u = new Uri(textBox1.Text); string request = "GET " + u.PathAndQuery + " HTTP/1.1\r\nHost: " + u.Host + "\r\nConnection: Close\r\n\r\n"; Byte[] buffer = Encoding.ASCII.GetBytes(request); e.SetBuffer(buffer, 0, buffer.Length); // отправляем асинхронный запрос s.SendAsync(e); } // изменение label-а, находящегося в основном потоке private void SetLabel(object args) { if (this.InvokeRequired) { this.Invoke(new MyDelegate(SetLabel), args); return; } label2.Text = args.ToString(); } } } 

In short: textBox1 contains a url , information is displayed in textBox2 (but I don't care where, the main thing is to get information from each socket, if there are several of them). Tell me, please, how to run several sockets at the same time and receive data from them?

  • Grabler write?) - Sergey

5 answers 5

If the threads are strongly interfered, you can look towards the fully asynchronous solution http://msdn.microsoft.com/ru-ru/library/bew39x2a.aspx . Instances of this class will not eat streams, plus they do not "prevent" other instances from creating / processing new connections / requests.

    in the documentation for Socket in MSDN, the first such cool example is: http://msdn.microsoft.com/ru-ru/library/system.net.sockets.socket.aspx it already has ready HTTP / GET, in your case I would make a class with an external event based on it, for example HTMLLoaded, which will work when the page is finished receiving, then we create our own class instance for each URL and subscribe to this event, then it remains to handle these calls

    for full asynchrony, it is better that the ConnectSocket () and SendRecieve () methods run in their own threads

    • Thanks, I will study. I'll try to make it work out. - Merlin

    I wrote a client for a webcam (the client needed a simple C ++ client)

    Did so

    1 - the "server" is written living at 127.0.0.1:80, the resource "http://127.0.0.1/test.txt" was requested from FireFox, the resulting package was saved as text.

    2 - we read the documentation on HTTP, in order to finally deal with the package received in paragraph 1, at this moment it comes to the realization that everything is not so difficult

    Bottom line: I found out that in order to receive a resource, I need to "create a connection to port 80 of the server" => "send an HTTP request there" => "receive (via the same connection) answer from the server" => "close the connection (if you continue to work, it is not necessary) "The server response is the header + the resource body, or just the header, which says that the resource will not be :)

    • If you create a connection on port 80, will all requests / responses from the sockets be simultaneously to this port or for each open socket its own port for receiving / transmitting? The answer from the server should come in parts on an open socket? because if the page size is unknown in advance, how much memory to allocate is unclear. And how do you know that the end of the received data has been reached? Parse for the presence of html-tags? Would it be very resource intensive? - Merlin
    • one
      There is only one port on the server, but each socket connection is a separate line; on one server port they hang themselves up to be a fool. The server response header contains data on the size of the incoming data (or a message that there will be no data), usually: read the header by byte -> allocate the memory as needed -> read the body - Kamikaze
    • And what are the ways to calculate the number of sockets per channel? Is it necessary to count the speed in each open socket and, based on monitoring, adjust? What will happen if there are more of them than the channel is calculated for, will they be put in a queue? - Merlin
    • The number of sockets will be limited to the maximum number of connections that the server holds (usually it limits it). In what sequence the server processes requests - especially its "server" business (in practice, I met only with parallel processing), the only thing that it is obliged is at least something to answer. However, trying to download a communication channel to a full one by creating MANY threads - bad karma, the more threads - the harder they are to synchronize, the more resources the program eats, and the server is not the only client. DownLoad Master - 5 threads :) - Kamikaze
    • Yes, I just because of the presence of threads wanted to go to sockets, because threads consume a lot of resources, it turns out that for every open socket need a thread or something? What is the point then? - Merlin

    if you need a page code can just fit WebRequest? http://msdn.microsoft.com/en-us/library/system.net.webrequest.aspx if you need to asynchronously, run in streams ...

    • Yes, the fact of the matter is that no threads are needed, I want to understand how the sockets work on the web: connection, processing errors returned by the server, sending. Now here's Google but to no avail. - Merlin
    • You decide what you need: to solve a production problem or learn how to work with sockets. - Modus
    • Your answer unfortunately does not suit me because it does not satisfy the question posed, and in particular with regards to sockets, but thanks anyway for participating. - Merlin

    try using the cURL library for hornbeam html code

    • yes, I already get the html code, only in one socket, I don’t understand how to organize the execution of several, maybe all these methods should be wrapped in a class and in a loop each time and call the instance method of this class? - Merlin