Projekt_SIK/server/uberProstyServer.c

77 lines
2.5 KiB
C

#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <unistd.h>
int main(void) {
char bufor[1024], rBufor[1024], tBufor[1024]; //wiadomosc
int gniazdo, gniazdo2, rGniazdo, tGniazdo;
struct sockaddr_in adr, rNadawca, tNadawca, adrS;
socklen_t dl = sizeof(struct sockaddr_in);
gniazdo = socket(PF_INET, SOCK_STREAM, 0);
gniazdo2 = socket(PF_INET, SOCK_STREAM, 0);
//adres do odbierania widomosci od klienta
adr.sin_family = AF_INET;
adr.sin_port = htons(44444); //port
adr.sin_addr.s_addr = INADDR_ANY;
//adres do wysylania widomosci do klienta
adrS.sin_family = AF_INET;
adrS.sin_port = htons(44445); //port
adrS.sin_addr.s_addr = INADDR_ANY;
printf("Odbieram na %s:%d\n", inet_ntoa(adr.sin_addr), ntohs(adr.sin_port));
printf("Wysylam na %s:%d\n", inet_ntoa(adrS.sin_addr), ntohs(adrS.sin_port));
//konfiguracja do odbierania wiadomosci
if (bind(gniazdo, (struct sockaddr*) &adr, sizeof(adr)) < 0) { //bind
printf("Bind nie powiodl sie.\n");
return 1;
}
if (listen(gniazdo, 10) < 0) { //listen
printf("Listen nie powiodl sie.\n");
return 1;
}
//konfiguracja do wysylania wiadomosci
if (bind(gniazdo2, (struct sockaddr*) &adrS, sizeof(adrS)) < 0) { //bind
printf("Bind nie powiodl sie.\n");
return 1;
}
if (listen(gniazdo2, 10) < 0) { //listen
printf("Listen nie powiodl sie.\n");
return 1;
}
printf("Polaczenia skonfigurowane ...\n");
if (fork() == 0){ //child wejdzie w to TUTAJ WYSYLAM WIDOMOSCI co 5 sekund
while ((tGniazdo = accept(gniazdo2, (struct sockaddr*) &tNadawca, &dl)) > 0) {
int licznik = 1;
while(1){
memset(tBufor, 0, 1024);
tBufor[1] = licznik + '0';
printf("Wysylam licznik\n");
send(tGniazdo, tBufor, 1024, 0);
licznik += 1;
sleep(3);
}
}
} else { //tutaj odbieram wiadomosci
while ((rGniazdo = accept(gniazdo, (struct sockaddr*) &rNadawca, &dl)) > 0) { //odbieranie
memset(rBufor, 0, 1024);
recv(rGniazdo, rBufor, 1024, 0);
printf("Wiadomosc od %s: %s\n", inet_ntoa(rNadawca.sin_addr), rBufor);
close(rGniazdo);
}
}
//do tego w sumie nigdy nie dojdziemy
close(gniazdo2);
close(gniazdo);
return 0;
}