Форум программистов, компьютерный форум, киберфорум
C/C++: WinAPI
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
 
Рейтинг 5.00/22: Рейтинг темы: голосов - 22, средняя оценка - 5.00
41 / 22 / 12
Регистрация: 07.12.2011
Сообщений: 114

Сокеты, send(), recv()

07.12.2012, 00:42. Показов 4483. Ответов 24
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
задача- пользователь ввел количество структур. заполнил их. Агенты-Клиенты работают просто так, в фоновом режиме почти. Сервер отправляет им структуру, они её принимают и сервер их отключает, смотрит есть ли еще в очереди помощник, обрабатывают и возвращают обратно(уже посчитав) Сервер выводит ответ.


C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#include<iostream>
#include<WinSock2.h>
#include<Windows.h>
#pragma comment(lib, "WSock32.lib")
using namespace std;
 
struct Zayavka
{
    int ID;
    int num1;
    int num2;
    int res;
    int oper;//1.+;2.-;3.*;4./;
    int time;
 
};
 
Zayavka *irr;
int kol;
int i;
 
void gener()
{
    while(i<kol)
    {  
        cout<<"Заявка №"<<i+1<<"\n";
        irr[i].ID=i+1;
        irr[i].res=0;
        irr[i].time=rand()%1000-700;
        cout<<"Введите число 1 : ";
        cin>>irr[i].num1;
        cout<<"Операция : ";
        char ch;
        cin>>ch;
        switch(ch)
        {
        case '+' : irr[i].oper=1; break;
            case '-' : irr[i].oper=2; break;
                case '*' : irr[i].oper=3; break;
                    case '/' : irr[i].oper=4; break;
 
        }
        cout<<"Введите число 2 : ";
        cin>>irr[i].num2;
        i++;
    }
}
 
int main()
{
    setlocale(LC_ALL, "Russian");
    cout<<"Введите количество операций: ";
    cin>>kol;
 
    irr=new Zayavka[kol];
    HANDLE *g = new HANDLE[1];
    i=0;
    g[0] = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)gener, 0, 0, 0);
    WaitForMultipleObjects(1, g, true, INFINITE);
 
    int Version;
    WSADATA wsaData;
    Version=MAKEWORD(2,2);
    WSAStartup(Version,&wsaData);
 
    SOCKET s = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
 
    struct sockaddr_in sin;
    sin.sin_family = AF_INET;
    sin.sin_port = htons(80);
    sin.sin_addr.s_addr = INADDR_ANY;
 
     int err = bind( s, (LPSOCKADDR)&sin, sizeof(sin) ); 
     err = listen( s, SOMAXCONN);
    
     int ot=0;
     int pr=0;
     while(pr<kol)
     {
    
         char kod[1];  
    sockaddr_in from;
    int fromlen=sizeof(from);
    SOCKET  s1 = accept(s,(struct sockaddr*)&from, &fromlen);
         err = recv(s1, kod, sizeof(kod), 0 ); //принимает код, что надо, отправить или принять
         if(kod[0]=='o')
         {
            err = send(s1, (char *)&irr[ot], sizeof(irr[ot]), 0 ); 
            ot++;
         }
         else  if(kod[0]=='p')
         {
             Zayavka Z;
            err = recv(s1, (char *)&Z, sizeof(Zayavka), 0 ); 
            irr[Z.ID].res=Z.res;
            pr++;
         }
         closesocket(s1);
     }
 
 
    for(int uuu=0;uuu<kol;uuu++)
    {   cout<<"Заявка №"<<irr[uuu].ID+1<<"\n";
              cout<<irr[uuu].num1;
              if(irr[uuu].oper==1)
                  cout<<"+";
              else if(irr[uuu].oper==2)
                  cout<<"-";
              else if(irr[uuu].oper==3)
                  cout<<"*";
              else if(irr[uuu].oper==4)
                  cout<<"/";
              cout<<irr[uuu].num2<<"="<<irr[uuu].res<<"\n";
    }
    WSACleanup();
    system("pause");
 
}

агент


C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include<iostream>
#include<WinSock2.h>
#include<Windows.h>
#pragma comment(lib, "WSock32.lib")
 
using namespace std;
 
 
struct Zayavka
{
    int ID;
    int num1;
    int num2;
    int res;
    int oper;//1.+;2.-;3.*;4./;
    int time;
 
};
 
int main()
{
    setlocale(LC_ALL, "Russian");
    int Version;
    WSADATA wsaData;
    Version=MAKEWORD(2,2);
    WSAStartup(Version,&wsaData);
 
int rc;
SOCKET s1 = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
 
        struct sockaddr_in anAddr;
        anAddr.sin_family = AF_INET;
        anAddr.sin_port = htons(80);
        anAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");//указываем айпи сервера
 
        for(;;)
        {
            connect(s1, (struct sockaddr *)&anAddr, sizeof(struct sockaddr));
            char kod[1];
            kod[0]='o';
 
              rc = send( s1, kod, sizeof(kod), 0 ); 
         Zayavka Z;
              rc = recv( s1, (char *)&Z, sizeof(Z), 0 ); 
 
              if(Z.oper==1)
                  Z.res=Z.num1+Z.num2;
              else if(Z.oper==2)
                  Z.res=Z.num1-Z.num2;
              else if(Z.oper==3)
                  Z.res=Z.num1*Z.num2;
              else if(Z.oper==4&&Z.num2!=0)
                  Z.res=Z.num1/Z.num2;
              else if(Z.oper==4&&Z.num2==0)
                  cout<<"Fail(Delenie na 0)";
 
              cout<<"Заявка №"<<Z.ID+1<<"\n";
              cout<<Z.num1;
              if(Z.oper==1)
                  cout<<"+";
              else if(Z.oper==2)
                  cout<<"-";
              else if(Z.oper==3)
                  cout<<"*";
              else if(Z.oper==4)
                  cout<<"/";
              cout<<Z.num2<<"="<<Z.res<<"\n";
 
              Sleep(Z.time);
 
           connect(s1, (struct sockaddr *)&anAddr, sizeof(struct sockaddr));
           kod[0]='p';
           rc = send( s1, kod, sizeof(kod), 0 ); 
           rc = send( s1, (char *)&Z, sizeof(Z), 0 ); 
        }
       closesocket(s1);
 
                WSACleanup();
                system("pause");
                return 0;
}
Добавлено через 1 минуту
из ошибок. уже в начале, при приеме агентом он выводит мусор, типа передал криво. как я понимаю.
потом еще принимает только одну заявку агент и обратно не отправляет. Получается сервер принял, что ему надо отправить. отправил, агент принял, выполнил мусор, и назад отправить видимо не может...

Добавлено через 8 минут
вот коменты некоторые добавил

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#include<iostream>
#include<WinSock2.h>
#include<Windows.h>
#pragma comment(lib, "WSock32.lib")
using namespace std;
 
struct Zayavka
{
    int ID;
    int num1;
    int num2;
    int res;
    int oper;//1.+;2.-;3.*;4./;
    int time;
 
};
 
Zayavka *irr;
int kol;//количество заявок
int i;//для заполнения 
 
void gener()
{
    while(i<kol)
    {  
        cout<<"Заявка №"<<i+1<<"\n";
        irr[i].ID=i+1;
        irr[i].res=0;
        irr[i].time=rand()%1000-700;
        cout<<"Введите число 1 : ";
        cin>>irr[i].num1;
        cout<<"Операция : ";
        char ch;
        cin>>ch;
        switch(ch)
        {
        case '+' : irr[i].oper=1; break;
            case '-' : irr[i].oper=2; break;
                case '*' : irr[i].oper=3; break;
                    case '/' : irr[i].oper=4; break;
 
        }
        cout<<"Введите число 2 : ";
        cin>>irr[i].num2;
        i++;
    }
}
 
int main()
{
    setlocale(LC_ALL, "Russian");
    cout<<"Введите количество операций: ";
    cin>>kol;
 
    irr=new Zayavka[kol];
    HANDLE *g = new HANDLE[1];
    i=0;
    g[0] = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)gener, 0, 0, 0);//заполним массив
    WaitForMultipleObjects(1, g, true, INFINITE);
 
    int Version;
    WSADATA wsaData;
    Version=MAKEWORD(2,2);
    WSAStartup(Version,&wsaData);
 
    SOCKET s = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
 
    struct sockaddr_in sin;
    sin.sin_family = AF_INET;
    sin.sin_port = htons(80);
    sin.sin_addr.s_addr = INADDR_ANY;
 
     int err = bind( s, (LPSOCKADDR)&sin, sizeof(sin) ); 
     err = listen( s, SOMAXCONN);
    
     int ot=0;//колество отправленных заявок
     int pr=0;//кол-во принятых
     while(pr<kol&&ot<kol)
     {
    
         char kod[1];  //чтобы принять код
    sockaddr_in from;
    int fromlen=sizeof(from);
    SOCKET  s1 = accept(s,(struct sockaddr*)&from, &fromlen);
         err = recv(s1, kod, sizeof(kod), 0 ); //принимает код, что надо, отправить или принять
         if(kod[0]=='o')//то надо отправить заявку
         {
            err = send(s1, (char *)&irr[ot], sizeof(irr[ot]), 0 );//вот тут отправляю ot-ый элемент, не знаю получиться ли 
            ot++;
         }
         else  if(kod[0]=='p')//если принять надо
         {
             Zayavka Z;//создали куда принимать
            err = recv(s1, (char *)&Z, sizeof(Zayavka), 0 ); //приняли заявку
            irr[Z.ID].res=Z.res;//записали результат
            pr++;
         }
         closesocket(s1);//в любом из действий отключаем связь, т.к в цикле, ищем следующего агента
     }
 
 
    for(int uuu=0;uuu<kol;uuu++)
    {   cout<<"Заявка №"<<irr[uuu].ID+1<<"\n";
              cout<<irr[uuu].num1;
              if(irr[uuu].oper==1)
                  cout<<"+";
              else if(irr[uuu].oper==2)
                  cout<<"-";
              else if(irr[uuu].oper==3)
                  cout<<"*";
              else if(irr[uuu].oper==4)
                  cout<<"/";
              cout<<irr[uuu].num2<<"="<<irr[uuu].res<<"\n";
    }
    WSACleanup();
    system("pause");
 
}

агент


C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include<iostream>
#include<WinSock2.h>
#include<Windows.h>
#pragma comment(lib, "WSock32.lib")
 
using namespace std;
 
 
struct Zayavka
{
    int ID;
    int num1;
    int num2;
    int res;
    int oper;//1.+;2.-;3.*;4./;
    int time;
 
};
 
int main()
{
    setlocale(LC_ALL, "Russian");
    int Version;
    WSADATA wsaData;
    Version=MAKEWORD(2,2);
    WSAStartup(Version,&wsaData);
 
int rc;
SOCKET s1 = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
 
        struct sockaddr_in anAddr;
        anAddr.sin_family = AF_INET;
        anAddr.sin_port = htons(80);
        anAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");//указываем айпи сервера
 
        for(;;)
        {
            connect(s1, (struct sockaddr *)&anAddr, sizeof(struct sockaddr));
            char kod[1];
            kod[0]='o';
 
              rc = send( s1, kod, sizeof(kod), 0 ); //отправляем что нужна заявка
         Zayavka Z;
              rc = recv( s1, (char *)&Z, sizeof(Z), 0 ); //принимаем заявку
 
              if(Z.oper==1)
                  Z.res=Z.num1+Z.num2;
              else if(Z.oper==2)
                  Z.res=Z.num1-Z.num2;
              else if(Z.oper==3)
                  Z.res=Z.num1*Z.num2;
              else if(Z.oper==4&&Z.num2!=0)
                  Z.res=Z.num1/Z.num2;
              else if(Z.oper==4&&Z.num2==0)
                  cout<<"Fail(Delenie na 0)";//выполнили её
 
              cout<<"Заявка №"<<Z.ID+1<<"\n";
              cout<<Z.num1;
              if(Z.oper==1)
                  cout<<"+";
              else if(Z.oper==2)
                  cout<<"-";
              else if(Z.oper==3)
                  cout<<"*";
              else if(Z.oper==4)
                  cout<<"/";
              cout<<Z.num2<<"="<<Z.res<<"\n";
 
              Sleep(Z.time);//задержка
 
           connect(s1, (struct sockaddr *)&anAddr, sizeof(struct sockaddr));//пытаемся связаться с сокетом, чтобы отпраивть ответ
           kod[0]='p';//хочу ответить
           rc = send( s1, kod, sizeof(kod), 0 ); //отправляем код
           rc = send( s1, (char *)&Z, sizeof(Z), 0 ); //отправляем заявку
        }
       closesocket(s1);//закрываем сокет. так как цикл бесконечен, заново  создаем и коннектимся
 
                WSACleanup();
                system("pause");
                return 0;
}
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
07.12.2012, 00:42
Ответы с готовыми решениями:

Hook на recv
Здравствуйте. Есть необходимость узнать, что у пользователя в браузере. Добрый человек на хабре подсказал поставить хук на сетевые...

Проблема с получением данных из буфера recv
Я заметил, что при получении данных через result = recv(client_sock, buf, sizeof(buf), 0); в buf записываются данные и огромное...

Функция recv принимает неизвестные данные
Проконтролировал отладчиком программу. Выяснил что клиент получает пустую строку т.е. (&quot;&quot;), хотя на сервере никакой отправки не...

24
Модератор
 Аватар для vxg
3409 / 2180 / 354
Регистрация: 13.01.2012
Сообщений: 8,461
15.12.2012, 23:54
Студворк — интернет-сервис помощи студентам
цикл завершиться когда соединиться. если соединения не будет будет крутиться вечно.
объяснить сложно, если это возможно я бы убрал разрывы соединения. может систему тошнить от того что вы создаете такое чудовищное количество сокетов в такое короткое время... хз
0
41 / 22 / 12
Регистрация: 07.12.2011
Сообщений: 114
17.12.2012, 00:19  [ТС]
ну и пока вопрос появился. про функцию select() что там и для чего и что делает. а то плохо гуглю наверное, пока мало понимаю. Понимаю что уже неблокирующие сокеты стали.

Добавлено через 22 минуты
может раз системе плохо, попробовать подольше ставить задержки? чтобы не сразу просил заявку, а через несколько секунд?

Добавлено через 23 часа 32 минуты
Все, программа работает. Преподаватель указал на две ошибки, исправил одну, уже заработало хорошо.

Ошибки, при sin_port = htons(80); заменил на порт (1234) потому что преподаватель сказал что 80 порт используется многими программами.

ну и потом еще для уверенности в сервере отправлял data d[i] а принимал data d заменил на принятие data d чтобы отличались) пока все работает)
0
Модератор
 Аватар для vxg
3409 / 2180 / 354
Регистрация: 13.01.2012
Сообщений: 8,461
17.12.2012, 09:50
Цитата Сообщение от pavlovnik Посмотреть сообщение
неблокирующие сокеты стали
нет, они по прежнему блокирующие, просто мы попытались исключить операции подразумевающие ожидание
Цитата Сообщение от pavlovnik Посмотреть сообщение
80 порт используется многими программами
мб
Цитата Сообщение от pavlovnik Посмотреть сообщение
отправлял data d[i] а принимал data d
ну тут уже не знаю как у вас там реализовано.
1
41 / 22 / 12
Регистрация: 07.12.2011
Сообщений: 114
18.12.2012, 01:32  [ТС]
C++
1
2
3
4
fd_set s_set = {1, {s}};
        timeval timeout = {0, 0};
        int select_res = select(0, &s_set, 0, 0, &timeout);
        if (select_res == SOCKET_ERROR) return -1;

нигде особенно про это не написано. можно рассказать по строкам что тут, и какие параметры. что передавать в сам select(), для чего он служит и т.д.)
0
Модератор
 Аватар для vxg
3409 / 2180 / 354
Регистрация: 13.01.2012
Сообщений: 8,461
18.12.2012, 09:13
Цитата Сообщение от pavlovnik Посмотреть сообщение
нигде особенно про это не написано
пишем select и нажимаем F1:
The Windows Sockets select function determines the status of one or more sockets, waiting if necessary.

int select (

int nfds,
fd_set FAR * readfds,
fd_set FAR * writefds,
fd_set FAR * exceptfds,
const struct timeval FAR * timeout
);


Parameters

nfds

[in] This argument is ignored and included only for the sake of compatibility.

readfds

[in/out] An optional pointer to a set of sockets to be checked for readability.

writefds

[in/out] An optional pointer to a set of sockets to be checked for writability

exceptfds

[in/out] An optional pointer to a set of sockets to be checked for errors.

timeout

[in] The maximum time for select to wait, or NULL for blocking operation.



Remarks

This function is used to determine the status of one or more sockets. For each socket, the caller can request information on read, write or error status. The set of sockets for which a given status is requested is indicated by an fd_set structure. The sockets contained within the fd_set structures must be associated with a single service provider. Upon return, the structures are updated to reflect the subset of these sockets which meet the specified condition, and select returns the number of sockets meeting the conditions. A set of macros is provided for manipulating an fd_set. These macros are compatible with those used in the Berkeley software, but the underlying representation is completely different.

The parameter readfds identifies those sockets which are to be checked for readability. If the socket is currently listening, it will be marked as readable if an incoming connection request has been received, so that an accept is guaranteed to complete without blocking. For other sockets, readability means that queued data is available for reading so that a recv or recvfrom is guaranteed not to block.
For connection-oriented sockets, readability can also indicate that a close request has been received from the peer. If the virtual circuit was closed gracefully, then a recv will return immediately with zero bytes read. If the virtual circuit was reset, then a recv will complete immediately with an error code, such as WSAECONNRESET. The presence of out-of-band data will be checked if the socket option SO_OOBINLINE has been enabled (see setsockopt).

The parameter writefds identifies those sockets which are to be checked for writability. If a socket is connecting (nonblocking), writability means that the connection establishment successfully completed. If the socket is not in the process of connecting, writability means that a send or sendto are guaranteed to succeed. However, they can block on a blocking socket if the len exceeds the amount of outgoing system buffer space available. [It is not specified how long these guarantees can be assumed to be valid, particularly in a multithreaded environment.]

The parameter exceptfds identifies those sockets which are to be checked for the presence of out-of-band data (see section Out-Of-Band data for a discussion of this topic) or any exceptional error conditions. Note that out-of-band data will only be reported in this way if the option SO_OOBINLINE is FALSE. If a socket is connecting (nonblocking), failure of the connect attempt is indicated in exceptfds. This specification does not define which other errors will be included.

Any two of readfds, writefds, or exceptfds can be given as NULL if no descriptors are to be checked for the condition of interest. At least one must be non-NULL, and any non-NULL descriptor set must contain at least one socket descriptor.
Summary: A socket will be identified in a particular set when select returns if:
readfds:

· If listening, a connection is pending, accept will succeed
· Data is available for reading (includes OOB data if SO_OOBINLINE is enabled)
· Connection has been closed/reset/terminated



writefds:

· If connecting (nonblocking), connection has succeeded
· Data can be sent



exceptfds:

· If connecting (nonblocking), connection attempt failed
· OOB data is available for reading (only if SO_OOBINLINE is disabled)



Four macros are defined in the header file WINSOCK2.H for manipulating and checking the descriptor sets. The variable FD_SETSIZE determines the maximum number of descriptors in a set. (The default value of FD_SETSIZE is 64, which can be modified by #defining FD_SETSIZE to another value before #including WINSOCK2.H.) Internally, socket handles in a fd_set are not represented as bit flags as in Berkeley Unix. Their data representation is opaque. Use of these macros will maintain software portability between different socket environments. The macros to manipulate and check fd_set contents are:

FD_CLR(s, *set)

Removes the descriptor s from set.

FD_ISSET(s, *set)

Nonzero if s is a member of the set. Otherwise, zero.

FD_SET(s, *set)

Adds descriptor s to set.

FD_ZERO(*set)

Initializes the set to the NULL set.



The parameter timeout controls how long the select can take to complete. If timeout is a null pointer, select will block indefinitely until at least one descriptor meets the specified criteria. Otherwise, timeout points to a struct timeval which specifies the maximum time that select should wait before returning. When select returns, the contents of the struct timeval are not altered. If the timeval is initialized to {0, 0}, select will return immediately; this is used to "poll" the state of the selected sockets. If this is the case, then the select call is considered nonblocking and the standard assumptions for nonblocking calls apply. For example, the blocking hook will not be called, and Windows Sockets will not yield.

Return Values

select returns the total number of descriptors which are ready and contained in the fd_set structures, zero if the time limit expired, or SOCKET_ERROR if an error occurred. If the return value is SOCKET_ERROR, WSAGetLastError can be used to retrieve a specific error code.

Comments

select has no effect on the persistence of socket events registered with WSAAsyncSelect or WSAEventSelect.

Error Codes

WSANOTINITIALISED A successful WSAStartup must occur before using this function.
WSAEFAULT The Windows Sockets implementation was unable to allocated needed resources for its internal operations, or the readfds, writefds, exceptfds, or timeval parameters are not part of the user address space.
WSAENETDOWN The network subsystem has failed.
WSAEINVAL The timeout value is not valid, or all three descriptor parameters were NULL.
WSAEINTR The (blocking) call was canceled through WSACancelBlockingCall.
WSAEINPROGRESS A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.
WSAENOTSOCK One of the descriptor sets contains an entry which is not a socket.


See Also

accept, connect, recv, recvfrom, send, WSAAsyncSelect, WSAEventSelect
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
18.12.2012, 09:13
Помогаю со студенческими работами здесь

WinAPI Socket, recv, узнать количество байт под буфер
Приветствую, форумчане! Пишу сетевое приложение. Возник вопрос с функцией recv, прием данных из сокета. В ней нужно указывать буфер и...

Сокеты: после вызова send программа зависает на функции recv
Извеняюсь за такое назание темы, но уже перепробовал 100 вариантов и постоянно выкидывает данное предупреждение, уже и не знаю что блин...

send/recv
Всем доброго времени суток. При написании простейшей клиент-серверной программы с возможностью передачи файлов, столкнулся с проблемой -...

send(.);recv(.);
Привет всем. Хроника событий: В сети имеются компьютеры a-сервер,b-клиент. 1. они соединяются через протокол TCP 2. ВНЕЗАПНО на...

send, recv и close
Что будет, если сервер пошлет данные на accept сокет и сразу же закроет этот сокет? Сможет ли клиент recv данные?


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
25
Ответ Создать тему
Новые блоги и статьи
Оттенки серого
Argus19 18.03.2026
Оттенки серого Нашёл в интернете 3 прекрасных модуля: Модуль класса открытия диалога открытия/ сохранения файла на Win32 API; Модуль класса быстрого перекодирования цветного изображения в оттенки. . .
SDL3 для Desktop (MinGW): Рисуем цветные прямоугольники с помощью рисовальщика SDL3 на Си и C++
8Observer8 17.03.2026
Содержание блога Финальные проекты на Си и на C++: finish-rectangles-sdl3-c. zip finish-rectangles-sdl3-cpp. zip
Символические и жёсткие ссылки в Linux.
algri14 15.03.2026
Существует два типа ссылок — символические и жёсткие. Ссылка в Linux — это запись в каталоге, которая может указывать либо на inode «файла-ИСТОЧНИКА», тогда это будет «жёсткая ссылка» (hard link),. . .
[Owen Logic] Поддержание уровня воды в резервуаре количеством включённых насосов: моделирование и выбор регулятора
ФедосеевПавел 14.03.2026
Поддержание уровня воды в резервуаре количеством включённых насосов: моделирование и выбор регулятора ВВЕДЕНИЕ Выполняя задание на управление насосной группой заполнения резервуара,. . .
делаю науч статью по влиянию грибов на сукцессию
anaschu 13.03.2026
прикрепляю статью
SDL3 для Desktop (MinGW): Создаём пустое окно с нуля для 2D-графики на SDL3, Си и C++
8Observer8 10.03.2026
Содержание блога Финальные проекты на Си и на C++: hello-sdl3-c. zip hello-sdl3-cpp. zip Результат:
Установка CMake и MinGW 13.1 для сборки С и C++ приложений из консоли и из Qt Creator в EXE
8Observer8 10.03.2026
Содержание блога MinGW - это коллекция инструментов для сборки приложений в EXE. CMake - это система сборки приложений. Здесь описаны базовые шаги для старта программирования с помощью CMake и. . .
Как дизайн сайта влияет на конверсию: 7 решений, которые реально повышают заявки
Neotwalker 08.03.2026
Многие до сих пор воспринимают дизайн сайта как “красивую оболочку”. На практике всё иначе: дизайн напрямую влияет на то, оставит человек заявку или уйдёт через несколько секунд. Даже если у вас. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru