Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <cstring>
- #include <unistd.h>
- #define PORT 6666
- #define SERV 127.0.0.1
- void err(const char *s)
- {
- perror(s);
- exit(1);
- }
- using namespace std;
- int main()
- {
- int sock_fd,new_sock,val;
- struct sockaddr_in s_addr;
- int addrlen = sizeof(s_addr);
- char buffer[255] = {0};
- char *hi = (char*)"Witamy na serwerze!\nNapis 'bye' konczy transmisje\n";
- char *bye = (char*)"Do nastepnego razu!\n";
- char *ok = (char*)"Przyjalem!\n";
- sock_fd = socket(AF_INET, SOCK_STREAM, 0); // tworzymy gniazdo IPV4, TCP
- if (sock_fd < 1) err("Blad otwierania gniazda!");
- s_addr.sin_family = AF_INET; //ipv4
- s_addr.sin_addr.s_addr = INADDR_ANY; // aktualny adres IP
- s_addr.sin_port = htons(PORT); //na sieciowy porzadek bajtow
- if (bind(sock_fd, (struct sockaddr *)&s_addr,sizeof(s_addr)) < 0)
- err("Blad podpinania portu");
- listen(sock_fd,3); //kolejka ustawiona na 3
- new_sock = accept(sock_fd, (struct sockaddr *)&s_addr,(socklen_t*)&addrlen); //polaczenie
- if (new_sock < 0) err("Blad akceptowania polaczen");
- send(new_sock, hi, strlen(hi),0); //wysylamy przywitanie
- do{
- bzero(buffer,sizeof(buffer)); //zeruje bufor
- val = recv(new_sock,buffer,sizeof(buffer),0);
- if (val<0) err("Blad odczytu z gniazda");
- send(new_sock, ok, strlen(ok),0);
- cout << "Otrzymano wiadomosc: " << buffer;
- } while (buffer[0] != 'b' || buffer[1] != 'y' || buffer[2] != 'e'); //czytamy, chyba, ze "bye"
- send(new_sock, bye, strlen(bye),0); //papa
- close(new_sock); //zamykamy polaczenie
- close(sock_fd); //gniazdo tez
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement