програмата е за linux, но е мрежова така че съвместимостта с темата на форума е пълна!
трябва да направя сървър (ще работи на linux) който приема връзки от
клиенти, обработва ги и щом клиента затвори връзката, да е готов да
приеме следващия.
кодът ми е по-долу, но има едим проблем: след затваряне на връзката
повикването на select() ми връща грешка: bad file descriptор! ще
съм ви много благодарен ако ми покажете какво пропускам, къде греша.
кодът е изчестен за форума, инъче има всички нужни проверки за грешки.
/*
Name: LinuxServ.exe
Description: server, reads from file and waits for WinClient to connect
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <winsock.h>
//linux specific headers
/*prototypes*/
int GetDataFromStr(char* str);
int main()
{
//socket variables
fd_set read_fds; // file descriptor list for select()
int sockfd, newfd; // listen on sockfd, new connection on newfd
int is_conected = 0; //bool
int is_receiving = 0; //bool
int bSucces = 0; //bool
int nbytes;
char buf[4097];
WSADATA wsaData;
WSAStartup(MAKEWORD(1,1), &wsaData)
FD_ZERO(&read_fds);// clear the read set
socket()
// loose the "address already in use" error message
// next line forces reusing of the port
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (void*)&yes, sizeof(int)))
//setting proto , port and IP
bind()
listen()
FD_SET(sockfd, &read_fds); // add the listener to the master set
// keep track of the biggest file descriptor
fdmax = sockfd; // so far, it’s this one
while(1)//CIKAL 1
{
is_conected = 0;
is_receiving = 0; // set them at beginning of the cicle
bSucces = 0;
while(1) //CIKAL 2
{
//next function will return when smth. happens on our sockfd
if (select(fdmax+1, &read_fds, NULL, NULL, NULL) == -1)
{
perror("select");
exit(1);
}
if (FD_ISSET(sockfd, &read_fds)) // we got new coonection
{
if(!is_conected)
{
// handle new connection
accept()
is_conected = 1;// conection enabled
if(newfd > sockfd)
{
fdmax = newfd;
}
FD_SET(newfd, &read_fds); //add newfd to monitor set
}//else i don't accept second conection
}//eof if (FD_ISSET(sockfd));
else if(FD_ISSET(newfd, &read_fds)) //client is sending
{
if ((nbytes = recv(newfd, buf, sizeof buf /sizeof(char), 0)) <= 0)
{
// got error or connection closed by client
printf("LinuxServ: Connection reset by remote side");
FD_CLR(newfd, &read_fds); // remove from master set
close(newfd); // bye!
is_conected = 0;
if (nbytes != 0)
perror("recv");/* някои програми изключват по този начин и
затова щом read() даде грешка затварям връзката! */
break; //must go out from cycle 2
}//eof if (nbytes = recv() <= 0)
else // we got some data from a client
{
buf[nbytes] = '\0'; //terminate the string before any operation
GetDataFromStr(buf)
}//we got some data from client
}
}//KRAY NA CIKAL 2
}//KRAY NA CIKAL 1
return 0;
}
//eof main()===================[/cpp]