5 – amaliy ish Mavzu


Download 61.64 Kb.
Sana22.05.2020
Hajmi61.64 Kb.
#108783
Bog'liq
5-os


5 – amaliy ish

Mavzu: Linux operatsion tizimida tarmoqda(Socket) C++ tilida dasturlash.

Linux operatsion tizimida soket interfeysi mavjud bo’lib, u orqali dasturlar boshqa kompyuterdagi dasturlar bilan o’zaro muvofiq aloqa o’rnatishi mumkin, bu esa klient-server ilovalar yaratishda qo’l keladi. Bu interfeys Windows operatsion tizimidagi Windows Sockets yoki WinSock spetsifikatsiyasi yordami bilan mavjuddir. Socketlar yordamida Linux va Unix oilasidagi operatsion tizimlar bir-birovi bilan aloqa qilishi mumkin. Lekin WinSock bilan to’liq muvofiqlik yo’q.

Quyida klient-server dasturini ko’rib chiqamiz. Ushbu dasturda klient qismdan klientdan so’rovni kutib turgan serverga xabar yobramiz, u biz yuborgan xabarga qo’shimcha qo’shib klientga qaytarib yuboradi.

Server qism:

#include

#include

#include

#include

#include

#include
int main() {

int server_sockfd, client_sockfd;

int server_len, client_len;

struct sockaddr_un server_address;

struct sockaddr_un client_address;

unlink("server_socket");

server_sockfd = socket(AF_UNIX, SOCK_STREAM, 0);

server_address.sun_family = AF_UNIX;

strcpy(server_address.sun_path, "server_socket");

server_len = sizeof(server_address);

bind(server_sockfd, (struct sockaddr *)&server_address, server_len);

listen(server_sockfd, 5);

while(1) {

char ch[20];

printf("Client kutib turibman seni:\n");

client_len = sizeof(client_address);

client_sockfd = accept(server_sockfd,

(struct sockaddr *)&client_address, &client_len);

read(client_sockfd, &ch, 20);

strcpy(ch+5," louser");

write(client_sockfd, &ch, 20);

close(client_sockfd);

}

}

Klient qism:



#include

#include

#include

#include

#include

#include


int main() {

int sockfd;

int len;

struct sockaddr_un address;

int result;

char ch[20] = "Hello";

sockfd = socket(AF_UNIX, SOCK_STREAM, 0);

address.sun_family = AF_UNIX;

strcpy(address.sun_path, "server_socket");

len = sizeof(address);

result = connect(sockfd, (struct sockaddr *)&address, len);

if (result == -1) {

perror("Serverga ulanishda xatolik");

exit(1);


}

write(sockfd, &ch, 20);

read(sockfd, &ch, 20);

printf("Serverdan yuborilgan javob = %s\n", ch);

close(sockfd);

exit(0);


}



Klient serverga “Hello” satrini yubordi va server uni qabul qilib “Hello louser” satrini klientga qaytarib yubordi.
Download 61.64 Kb.

Do'stlaringiz bilan baham:




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling