Knowledge Base Nr: 00020 socketserver.cpp - http://www.swe-kaiser.de

Downloads:

linux: template consolenprogramm socketserver (non-blocking input mit curses)

  
//build: g++ main.cpp -o myname -lncurses


#include <iostream.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <termios.h>
#include <signal.h>
#include <string.h>

#include <curses.h>

#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>


///////////globale definitionen//////////////////////////



//////////////////main/////////////////////////////////////////
//#define TRACE
#define TRACE printf

#define PORTNO 4711
#define MAXCLIENTS 32
#define MAXBUFFER 4096

int main(int argc, char *argv[])
{
initscr();
cbreak();
fcntl(fileno(stdin), F_SETFL, fcntl(fileno(stdin), F_GETFL) | O_NONBLOCK);

printf("*** %s\r\n*** usage: %s [a] [b] [c]\r\n", argv[0], argv[0]);
TRACE("* args: %s", argv[0]);
for (int n=1; n<argc; n++)
TRACE(" [%s]", argv[n]);
TRACE("\r\n");

int sockfd = socket(PF_INET, SOCK_STREAM, 0);
if (sockfd<0)
{
printf("ERROR: anlegen socket. errno: %d strerror: %s\r\n", errno, strerror);
return 1;
}

//zulassen: socket sofort wiederbenutzbar
int i = 1;
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));

struct sockaddr_in adresse;
adresse.sin_family = AF_INET;
adresse.sin_port = htons(PORTNO);
memset(&adresse.sin_addr, 0, sizeof(adresse.sin_addr));

int nRes = bind(sockfd, (struct sockaddr*)&adresse, sizeof(adresse));
if (nRes != 0)
{
printf("ERROR: bind. errno: %d strerror: %s\r\n", errno, strerror);
return 1;
}

nRes = listen(sockfd, MAXCLIENTS);
if (nRes != 0)
{
printf("ERROR: listen. errno: %d strerror: %s\r\n", errno, strerror);
return 1;
}

size_t adrlen = sizeof(struct sockaddr_in);
TRACE("warten auf clients...\r\n"); fflush(stdout);

//////////
int connfd;

while ((connfd = accept(sockfd, (struct sockaddr*)&adresse, &adrlen)) >= 0)
{
if (connfd<0)
{
printf("ERROR: accept. errno: %d strerror: %s\r\n", errno, strerror);
return 1;
}

TRACE("client meldet sich an!\r\n"); fflush(stdout);

char puffer[MAXBUFFER];
int i=0;
while (1)
{
nRes = read(connfd, &puffer[i], 1);
if (nRes<0)
{
printf("ERROR: read. errno: %d strerror: %s\r\n", errno, strerror);
return 1;
}

//echo
nRes = write(connfd, &puffer[i], 1);
if (nRes<0)
{
printf("ERROR: write. errno: %d strerror: %s\r\n", errno, strerror);
return 1;
}


if (puffer[i] == '\n')
{
puffer[i] = 0;
printf("client: %s\r\n", puffer); fflush(stdout);
i = 0;
}
else
{
i++;
}
}

close(connfd);
}
///////

close(sockfd);

return EXIT_SUCCESS;
}